Peterfei

上主是我的牧者,我实在一无所缺


  • 首页

  • 归档

  • 标签

如何编写Dockerfile

发表于 2019-04-18   |   分类于 Docker   |  

示例

假设我们需要使用Docker运行一个Node.js应用

1
2
3
4
5
6
7
8
9
10
FROM ubuntu
ADD . /app
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y nodejs ssh mysql
RUN cd /app && npm install
CMD mysql & sshd & npm start

构建镜像:

1
docker build -t mydocker .

编写.dockerignore文件

构建镜像时,Docker需要先准备context ,将所有需要的文件收集到进程中。默认的context包含Dockerfile目录中的所有文件,但是实际上,我们并不需要.git目录,node_modules目录等内容。 .dockerignore 的作用和语法类似于 .gitignore,可以忽略一些不需要的文件,这样可以有效加快镜像构建时间,同时减少Docker镜像的大小。示例如下:

1
2
3
.git/
node_modules/

容器只运行单个应用

从技术角度讲,你可以在Docker容器中运行多个进程。你可以将数据库,前端,后端,ssh,supervisor都运行在同一个Docker容器中。但是,这会让你非常痛苦:

  • 非常长的构建时间(修改前端之后,整个后端也需要重新构建)
  • 非常大的镜像大小
  • 多个应用的日志难以处理
  • 横向扩展时非常浪费资源(不同的应用需要运行的容器数并不相同)
  • 僵尸进程问题 - 你需要选择合适的init进程

因此,我建议大家为每个应用构建单独的Docker镜像,然后使用 Docker Compose 运行多个Docker容器。

现在,我从Dockerfile中删除一些不需要的安装包,另外,SSH可以用docker exec替代。示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
FROM ubuntu
ADD . /app
RUN apt-get update
RUN apt-get upgrade -y
# we should remove ssh and mysql, and use
# separate container for database
RUN apt-get install -y nodejs # ssh mysql
RUN cd /app && npm install
CMD npm start

将多个RUN指令合并为一个

Docker镜像是分层的,下面这些知识点非常重要:

  • Dockerfile中的每个指令都会创建一个新的镜像层。
  • 镜像层将被缓存和复用
  • 当Dockerfile的指令修改了,复制的文件变化了,或者构建镜像时指定的变量不同了,对应的镜像层缓存就会失效
  • 某一层的镜像缓存失效之后,它之后的镜像层缓存都会失效
  • 镜像层是不可变的,如果我们再某一层中添加一个文件,然后在下一层中删除它,则镜像中依然会包含该文件(只是这个文件在Docker容器中不可见了)。

Docker镜像类似于洋葱。它们都有很多层。为了修改内层,则需要将外面的层都删掉。记住这一点的话,其他内容就很好理解了。

现在,我们将所有的RUN指令合并为一个。同时把apt-get upgrade删除,因为它会使得镜像构建非常不确定(我们只需要依赖基础镜像的更新就好了)

1
2
3
4
5
6
7
8
9
10
FROM ubuntu
ADD . /app
RUN apt-get update \
&& apt-get install -y nodejs \
&& cd /app \
&& npm install
CMD npm start

记住一点,我们只能将变化频率一样的指令合并在一起。将node.js安装与npm模块安装放在一起的话,则每次修改源代码,都需要重新安装node.js,这显然不合适。因此,正确的写法是这样的:

1
2
3
4
5
6
7
FROM ubuntu
RUN apt-get update && apt-get install -y nodejs
ADD . /app
RUN cd /app && npm install
CMD npm start

基础镜像的标签不要用latest

当镜像没有指定标签时,将默认使用latest 标签。因此, FROM ubuntu 指令等同于FROM ubuntu:latest。当时,当镜像更新时,latest标签会指向不同的镜像,这时构建镜像有可能失败。如果你的确需要使用最新版的基础镜像,可以使用latest标签,否则的话,最好指定确定的镜像标签。

示例Dockerfile应该使用16.04作为标签。

1
2
3
4
5
6
7
FROM ubuntu:16.04 # it's that easy!
RUN apt-get update && apt-get install -y nodejs
ADD . /app
RUN cd /app && npm install
CMD npm start

每个RUN指令后删除多余文件

假设我们更新了apt-get源,下载,解压并安装了一些软件包,它们都保存在/var/lib/apt/lists/目录中。但是,运行应用时Docker镜像中并不需要这些文件。我们最好将它们删除,因为它会使Docker镜像变大。

示例Dockerfile中,我们可以删除/var/lib/apt/lists/目录中的文件(它们是由apt-get update生成的)。

1
2
3
4
5
6
7
8
9
10
11
ROM ubuntu:16.04
RUN apt-get update \
&& apt-get install -y nodejs \
# added lines
&& rm -rf /var/lib/apt/lists/*
ADD . /app
RUN cd /app && npm install
CMD npm start

选择合适的基础镜像(alpine版本最好)

在示例中,我们选择了ubuntu作为基础镜像。但是我们只需要运行node程序,有必要使用一个通用的基础镜像吗?node镜像应该是更好的选择。

1
2
3
4
5
6
7
8
FROM node
ADD . /app
# we don't need to install node
# anymore and use apt-get
RUN cd /app && npm install
CMD npm start

更好的选择是alpine版本的node镜像。alpine是一个极小化的Linux发行版,只有4MB,这让它非常适合作为基础镜像。

1
2
3
4
5
6
FROM node:7-alpine
ADD . /app
RUN cd /app && npm install
CMD npm start

设置WORKDIR和 CMD

WORKDIR指令可以设置默认目录,也就是运行RUN / CMD / ENTRYPOINT指令的地方。

CMD指令可以设置容器创建是执行的默认命令。另外,你应该讲命令写在一个数组中,数组中每个元素为命令的每个单词(参考官方文档)。

1
2
3
4
5
6
7
FROM node:7-alpine
WORKDIR /app
ADD . /app
RUN npm install
CMD ["npm", "start"]

使用ENTRYPOINT (可选)

ENTRYPOINT指令并不是必须的,因为它会增加复杂度。ENTRYPOINT是一个脚本,它会默认执行,并且将指定的命令错误其参数。它通常用于构建可执行的Docker镜像。entrypoint.sh如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env sh
# $0 is a script name,
# $1, $2, $3 etc are passed arguments
# $1 is our command
CMD=$1
case "$CMD" in
"dev" )
npm install
export NODE_ENV=development
exec npm run dev
;;
"start" )
# we can modify files here, using ENV variables passed in
# "docker create" command. It can't be done during build process.
echo "db: $DATABASE_ADDRESS" >> /app/config.yml
export NODE_ENV=production
exec npm start
;;
* )
# Run custom command. Thanks to this line we can still use
# "docker run our_image /bin/bash" and it will work
exec $CMD ${@:2}
;;
esac

示例Dockerfile:

1
2
3
4
5
6
7
8
9
FROM node:7-alpine
WORKDIR /app
ADD . /app
RUN npm install
ENTRYPOINT ["./entrypoint.sh"]
CMD ["start"]

可以使用如下命令运行该镜像:

1
2
3
4
5
6
7
8
# 运行开发版本
docker run our-app dev
# 运行生产版本
docker run our-app start
# 运行bash
docker run -it our-app /bin/bash

COPY与ADD优先使用前者

1
2
3
4
5
6
7
8
9
FROM node:7-alpine
WORKDIR /app
COPY . /app
RUN npm install
ENTRYPOINT ["./entrypoint.sh"]
CMD ["start"]

合理调整COPY与RUN的顺序

我们应该把变化最少的部分放在Dockerfile的前面,这样可以充分利用镜像缓存。

示例中,源代码会经常变化,则每次构建镜像时都需要重新安装NPM模块,这显然不是我们希望看到的。因此我们可以先拷贝package.json,然后安装NPM模块,最后才拷贝其余的源代码。这样的话,即使源代码变化,也不需要重新安装NPM模块。

1
2
3
4
5
6
7
8
9
10
FROM node:7-alpine
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
ENTRYPOINT ["./entrypoint.sh"]
CMD ["start"]

设置默认的环境变量,映射端口和数据卷

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FROM node:7-alpine
ENV PROJECT_DIR=/app
WORKDIR $PROJECT_DIR
COPY package.json $PROJECT_DIR
RUN npm install
COPY . $PROJECT_DIR
ENV MEDIA_DIR=/media \
NODE_ENV=production \
APP_PORT=3000
VOLUME $MEDIA_DIR
EXPOSE $APP_PORT
ENTRYPOINT ["./entrypoint.sh"]
CMD ["start"]

添加HEALTHCHECK

运行容器时,可以指定–restart always选项。这样的话,容器崩溃时,Docker守护进程(docker daemon)会重启容器。对于需要长时间运行的容器,这个选项非常有用。但是,如果容器的确在运行,但是不可(陷入死循环,配置错误)用怎么办?使用HEALTHCHECK指令可以让Docker周期性的检查容器的健康状况。我们只需要指定一个命令,如果一切正常的话返回0,否则返回1。示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
FROM node:7-alpine
LABEL maintainer "jakub.skalecki@example.com"
ENV PROJECT_DIR=/app
WORKDIR $PROJECT_DIR
COPY package.json $PROJECT_DIR
RUN npm install
COPY . $PROJECT_DIR
ENV MEDIA_DIR=/media \
NODE_ENV=production \
APP_PORT=3000
VOLUME $MEDIA_DIR
EXPOSE $APP_PORT
HEALTHCHECK CMD curl --fail http://localhost:$APP_PORT || exit 1
ENTRYPOINT ["./entrypoint.sh"]
CMD ["start"]

记_给公司Unity小组实现的基于Sqlite缓存Cache类

发表于 2019-04-18   |   分类于 Unity   |  

需求

  1. 所有线上接口管理至本地缓存
  2. 使用面向对象
  3. db使用sqlite

设计思路

线上拉取数据,缓存至本地,读取本地版本,对比线上版本号,如有更新,更新本地数据库数据,如没有,则读取本地.

核心代码

IDbDao.cs 接口定义

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assets.Scripts.DbDao
{
public interface IDbDao<T> where T : class, new()
{
void setCache(string r);
}
}

CacheOption.cs 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Assets.Scripts.Repository;
using Assets.Scripts.Model;
using Assets.Scripts.Infrastructure;
using UnityEngine;
using Newtonsoft.Json;
namespace Assets.Scripts.DbDao
{
public class CacheOption<T> : IDbDao<T> where T : class, new()
{
public void setCache_dbPath(string r, string path, bool is_append = false)
{
var repository = new RemoteRepository<GetStruct>();
repository.Get<Response<T>>(r, (response) =>
{
Debug.Log(JsonConvert.SerializeObject(response));
if (response.List != null && response.List.Count != 0)
{
var db = new DbRepository<T>();
db.CreateDb(path);
if (!is_append)
{
db.DropTable();
}
db.CreateTable();
db.InsertAll(response.List);//更新远程数据源
db.Close();
}
else
{
Debug.Log("Struct List data is null ");
}
});
}
//实现写入缓存共有类
public void setCache(string r)
{
var repository = new RemoteRepository<GetStruct>();
var version = new DbRepository<TableVersions>();
version.DataService("vesali.db");
version.CreateTable();
TableVersions tv = version.SelectOne<TableVersions>((tmpT) =>
{
if (tmpT.table_name == typeof(T).Name)
{
return true;
}
return false;
});
var struct_version = "-1";
if (tv != null)
{
struct_version = tv.version;
}
repository.Get<Response<T>>(r, new GetStruct { Version = struct_version, device = SystemInfo.deviceUniqueIdentifier, os = Enum.GetName(typeof(asset_platform), PublicClass.platform) , level = ((int)PublicClass.Quality).ToString(), softVersion = PublicClass.get_version() }, (response) =>
{
if (response.List != null && response.List.Count != 0)
{
Debug.Log("============读取数据库缓存更新,从远程拉取数据,更新版本号=================== ");
//如果有数据,更新数据和版本
if (tv == null)
{
version.Insert(new TableVersions { table_name = typeof(T).Name, version = response.maxVersion });
}
else
{
version.Update(new TableVersions { table_name = typeof(T).Name, version = response.maxVersion });
}
version.Close();
var db = new DbRepository<T>();
db.DataService("vesali.db");
db.DropTable();
db.CreateTable();
db.InsertAll(response.List);//更新远程数据源
db.Close();
}
else
{
Debug.Log("Struct List data is null ");
// Debug.Log("============读取数据库缓存=================== ");
//读取数据库缓存
}
PublicClass.data_list_count++;
});
//throw new NotImplementedException();
}
}
}

IRepository.cs 对基本数据操作接口定义,如增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assets.Scripts.Repository
{
public interface IRepository<T> where T:class,new()
{
void Insert(T instance);
void Delete(T instance);
void Update(T instance);
IEnumerable<T> Select(Func<T,bool> func );
}
}

DbRepository.cs数据库脚本实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLite4Unity3d;
using UnityEngine;
namespace Assets.Scripts.Repository
{
public class DbRepository<T> : IRepository<T> where T : class, new()
{
//public delegate void DoConnection(String str);
private SQLiteConnection _connection;
//private string v;
//public DbRepository(string v)
//{
// this.v = v;
//}
public void CreateTable()
{
_connection.CreateTable<T>();
}
public TableQuery<T> getTableQuerry()
{
return _connection.Table<T>();
}
public void DropTable()
{
_connection.DropTable<T>();
}
public void Delete(T instance)
{
try
{
_connection.Delete(instance);
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public void Insert(T instance)
{
try
{
_connection.Insert(instance);
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public void InsertAll(T[] instance)
{
try
{
_connection.InsertAll(instance);
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public void InsertAll(List<T> instance)
{
try
{
_connection.InsertAll(instance);
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public T SelectOne<R>(Func<T, bool> func) where R : class, new()
{
return _connection.Table<T>().Where(func).FirstOrDefault();
}
public IEnumerable<T> Select<R>(Func<T, bool> func) where R : class, new()
{
return _connection.Table<T>().Where(func);
}
public void Update(T t)
{
_connection.Update(t);
}
public void Close()
{
try
{
_connection.Close();
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public void CreateDb(string dbPath)
{
_connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
}
public void DataService(string DatabaseName)
{
#if UNITY_EDITOR
var dbPath = string.Format("{0}/{1}", PublicClass.vesal_db_path, DatabaseName); //string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
#else
var filepath = string.Format("{0}/{1}",PublicClass.vesal_db_path, DatabaseName);
var dbPath = filepath;
// var dbPath = loadDb;
#endif
_connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
//DebugLog.DebugLogInfo("Final PATH: " + dbPath);
}
public IEnumerable<T> Select(Func<T, bool> func)
{
throw new NotImplementedException();
}
}
}

RemoteRepository.cs 接口类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Text;
using Assets.Scripts.Infrastructure;
using UnityEngine;
using Assets.Scripts.Network;
using UnityEngine;
using Newtonsoft.Json;
namespace Assets.Scripts.Repository
{
public class RemoteRepository<T> where T : class, new()
{
public ISerializer Serializer { get; set; }
public RemoteRepository(ISerializer serializer = null)
{
Serializer = serializer ?? SerializerJson.Instance;
}
public void Get<R>(string url, T instance, Action<R> onSuccess) where R : class, new()
{
var parameters = HttpUtility.BuildParameters(instance, new StringBuilder("?"));
var httpRequest = new HttpRequest
{
Url = url,
Method = HttpMethod.Get,
Parameters = parameters
};
Debug.Log(httpRequest.Url + httpRequest.Parameters);
HttpClient.Instance.SendAsync(httpRequest, httpResponse =>
{
if (httpResponse.IsSuccess)
{
R r = JsonConvert.DeserializeObject<R>(httpResponse.Data);
onSuccess(r);
}
//TODO:异常处理
});
}
public void Get<R>(string url, Action<R> onSuccess) where R : class, new()
{
// var parameters = HttpUtility.BuildParameters(instance, new StringBuilder("?"));
var httpRequest = new HttpRequest
{
Url = url,
Method = HttpMethod.Get,
// Parameters = parameters
};
HttpClient.Instance.SendAsync(httpRequest, httpResponse =>
{
if (httpResponse.IsSuccess)
{
R r = JsonConvert.DeserializeObject<R>(httpResponse.Data);
Debug.Log("json str :" + r);
onSuccess(r);
}
//TODO:异常处理
});
}
public void Post<R>(string url, T instance, Action<R> onSuccess) where R : class, new()
{
var parameters = HttpUtility.BuildParameters(instance, new StringBuilder());
var httpRequest = new HttpRequest
{
Url = url,
Method = HttpMethod.Post,
Parameters = parameters
};
HttpClient.Instance.SendAsync(httpRequest, httpResponse =>
{
if (httpResponse.IsSuccess)
{
//TODO:判断是否有Data
onSuccess(Serializer.Deserialize<R>(httpResponse.Data));
}
});
}
public void Test()
{
Debug.Log("Hello...");
}
}
}

Response.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assets.Scripts.Infrastructure
{
[System.Serializable]
public class Response<T>
{
public string msg;
public int code;
public List<T> List;
public string maxVersion;
}
}

HttpUtility.cs http操作类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assets.Scripts.Infrastructure
{
public class HttpUtility
{
public static string BuildParameters<T>(T instance, StringBuilder sb) where T:class,new()
{
foreach (var property in instance.GetType().GetProperties())
{
var propertyName = property.Name;
var value = property.GetValue(instance, null);
sb.Append(propertyName + "=" + value + "&");
}
return sb.ToString().TrimEnd('&');
}
}
}

ISerializer.cs 格式化接口

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assets.Scripts.Infrastructure
{
public interface ISerializer
{
string Serialize<T>(T obj, bool readableOutput = false) where T : class, new();
T Deserialize<T>(string json) where T : class, new();
}
}

SerializerJson.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts.Infrastructure
{
public class SerializerJson:ISerializer
{
public static readonly SerializerJson Instance=new SerializerJson();
private SerializerJson()
{
}
public string Serialize<T>(T obj, bool readableOutput = false) where T : class, new()
{
throw new NotImplementedException();
}
public T Deserialize<T>(string json) where T : class, new()
{
return JsonUtility.FromJson<T>(json);
}
}
}

SQLite.cs

查看源码

HttpMethod.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assets.Scripts.Infrastructure
{
public enum HttpMethod
{
Get,
Post
}
}

Model实例

TableVersions.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using SQLite4Unity3d;
namespace Assets.Scripts.Model
{
[Serializable]
public class TableVersions
{
[PrimaryKey]
public string table_name { get; set; }
public string version { get; set; }
}
}

GetStruct.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
namespace Assets.Scripts.Model
{
class GetStruct
{
public string Version { get; set; }
public string UpdateUrlUuid { get; set; }
public string device { get; set; }
public string os { get; set; }
public string level { get; set; }
public string softVersion { get; set; }
}
}

使用示例

1
2
var cache_CommonLib = new CacheOption<GetStruct>();
cache_CommonLib.setCache(PublicClass.server_ip+'v1/app/api')

docker笔记01

发表于 2019-04-17   |   分类于 docker   |  

安装 Docker

Mac 上的安装

1
brew cask install docker

安装完成之后,执行 hello-world 试一下:

1
$ docker run hello-world
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/

启动Nginx服务

1
docker run -d -p 80:80 --restart=always nginx:latest

-p 表示宿主机IP:容器IP
--restart 重启模式,设置 always,每次启动 docker 都会启动 nginx 容器

进入容器

1
docker exec -it 4591552a4185 bash

参数说明:

exec 对容器操作
-it 分配伪tty
4591552a4185容器ID
bash交互程序为bash

Docker 提供数据挂载的功能,即可以指定容器内的某些路径映射到宿主机器上,修改命令,添加 -v 参数,启动新的容器。

1
docker run -d -p 80:80 -v ~/docker-demo/nginx-htmls:/usr/share/nginx/html/ --restart=always nginx:latest

启动成功之后,docker 会帮你生成目录 ~/docker-demo/nginx-htmls

停止运行

1
docker stop 4591552a4185

删除容器

1
docker rm 4591552a4185

分配IP给宿主机

1
sudo ifconfig lo0 alias 192.168.64.0/24

访问 http://192.168.64.0:8080

ReactNative之Realm预加载数据

发表于 2019-04-11   |   分类于 前端   |  

realm 数据预加载

Require Env:
1
2
3
npm i realm
npm i react-native-fs
react-native link

分别拷贝数据库至原生公用目录

Android端

android/app/src/main/assets/demo.realm

IOS端

Build Phases->Copy Bundle Resources->demo.realm

前端

执行Realm 提供的copyBundledRealmFiles,可以将共用的数据库文件拷贝至应用安装的Documents目录.

Realm.copyBundledRealmFiles();

实例
prepare-realm-data-demo

记IOS开发之我是如何解决react-native-unity-view插件在Product模式闪退

发表于 2019-04-10   |   分类于 IOS   |  

事件起因:

公司在使用react-native开发解剖3D软件,需要和unity进行融合,在组件选择上,使用了react-native-unity-view这款插件,在融合过程中,踩了很多坑,花费精力最大的,是年后IOS升级为12.1后,集成方案集中出现闪退.

Issue #79

iOS crashes on launch in release builds only #79

Cash log 如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Thread 7 name: com.facebook.react.JavaScript
Thread 7 Crashed:
0 libsystem_kernel.dylib 0x00000001fbbbd104 __pthread_kill + 8
1 libsystem_pthread.dylib 0x00000001fbc3ca00 pthread_kill$VARIANT$armv81 + 296
2 libsystem_c.dylib 0x00000001fbb14d78 abort + 140
3 libsystem_malloc.dylib 0x00000001fbc11768 _malloc_put + 0
4 libsystem_malloc.dylib 0x00000001fbc11924 malloc_report + 64
5 libsystem_malloc.dylib 0x00000001fbc042d0 free + 376
6 libc++.1.dylib 0x00000001fb1bf120 std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_string+ 258336 () + 32
7 UnityTest 0x0000000102de23a4 std::__1::__vector_base<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >::~__vector_base() + 730020 (vector:451)
8 UnityTest 0x0000000103385214 facebook::react::ModuleRegistry::getConfig+ 6640148 (std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) + 100
9 UnityTest 0x0000000103394168 facebook::react::JSCNativeModules::createModule+ 6701416 (std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, OpaqueJSContext const*) + 292
10 UnityTest 0x0000000103393cc8 facebook::react::JSCNativeModules::getModule+ 6700232 (OpaqueJSContext const*, OpaqueJSString*) + 188
11 UnityTest 0x000000010338e85c OpaqueJSValue const* (*facebook::react::(anonymous namespace)::exceptionWrapMethod<&(facebook::react::JSCExecutor::getNativeModule(OpaqueJSValue*, OpaqueJSString*))>())(OpaqueJSContext const*, OpaqueJSValue*, OpaqueJSString*, OpaqueJSValue const**)::funcWrapper::call+ 6678620 (OpaqueJSContext const*, OpaqueJSValue*, OpaqueJSString*, OpaqueJSValue const**) + 104
12 JavaScriptCore 0x0000000203350404 JSC::JSCallbackObject<JSC::JSDestructibleObject>::getOwnPropertySlot+ 574468 (JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&) + 340
13 JavaScriptCore 0x0000000203a354f0 llint_slow_path_get_by_id + 2008
14 JavaScriptCore 0x0000000203328928 llint_entry + 11528
15 JavaScriptCore 0x000000020332d134 llint_entry + 29972
16 JavaScriptCore 0x000000020332d134 llint_entry + 29972
17 JavaScriptCore 0x000000020332d134 llint_entry + 29972
18 JavaScriptCore 0x000000020332d134 llint_entry + 29972
19 JavaScriptCore 0x000000020332d134 llint_entry + 29972
20 JavaScriptCore 0x0000000203325a1c vmEntryToJavaScript + 300
21 JavaScriptCore 0x000000020399bfe4 JSC::Interpreter::executeProgram+ 7176164 (JSC::SourceCode const&, JSC::ExecState*, JSC::JSObject*) + 9620
22 JavaScriptCore 0x0000000203b77218 JSC::evaluate+ 9122328 (JSC::ExecState*, JSC::SourceCode const&, JSC::JSValue, WTF::NakedPtr<JSC::Exception>&) + 316
23 JavaScriptCore 0x000000020334e634 JSEvaluateScript + 472
24 UnityTest 0x000000010336dad0 facebook::react::evaluateScript+ 6544080 (OpaqueJSContext const*, OpaqueJSString*, OpaqueJSString*) + 80
25 UnityTest 0x000000010338c918 facebook::react::JSCExecutor::loadApplicationScript+ 6670616 (std::__1::unique_ptr<facebook::react::JSBigString const, std::__1::default_delete<facebook::react::JSBigString const> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) + 528
26 UnityTest 0x0000000103392ba4 std::__1::__function::__func<facebook::react::NativeToJsBridge::loadApplication(std::__1::unique_ptr<facebook::react::RAMBundleRegistry, std::__1::default_delete<facebook::react::RAMBundleRegistry> >, std::__1::unique_ptr<facebook::react::JSBigString const, std::__1::default_delete<facebook::react::JSBigString const> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)::$_0, std::__1::allocator<facebook::react::NativeToJsBridge::loadApplication(std::__1::unique_ptr<facebook::react::RAMBundleRegistry, std::__1::default_delete<facebook::react::RAMBundleRegistry> >, std::__1::unique_ptr<facebook::react::JSBigString const, std::__1::default_delete<facebook::react::JSBigString const> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)::$_0>, void (facebook::react::JSExecutor*)>::operator()+ 6695844 (facebook::react::JSExecutor*&&) + 144
27 UnityTest 0x0000000103393ba8 std::__1::function<void (facebook::react::JSExecutor*)>::operator()+ 6699944 (facebook::react::JSExecutor*) const + 40
28 UnityTest 0x000000010330c9cc facebook::react::tryAndReturnError(std::__1::function<void + 6146508 ()> const&) + 24
29 UnityTest 0x0000000103302528 facebook::react::RCTMessageThread::tryFunc(std::__1::function<void + 6104360 ()> const&) + 24
30 CoreFoundation 0x00000001fbfb6408 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
31 CoreFoundation 0x00000001fbfb5d08 __CFRunLoopDoBlocks + 272
32 CoreFoundation 0x00000001fbfb1220 __CFRunLoopRun + 2376
33 CoreFoundation 0x00000001fbfb05b8 CFRunLoopRunSpecific + 436
34 UnityTest 0x00000001032e36a4 +[RCTCxxBridge runRunLoop] + 264
35 Foundation 0x00000001fcad73b0 __NSThread__start__ + 1040
36 libsystem_pthread.dylib 0x00000001fbc412fc _pthread_body + 128
37 libsystem_pthread.dylib 0x00000001fbc4125c _pthread_start + 48
38 libsystem_pthread.dylib 0x00000001fbc44d08 thread_start + 4
最初的解决方案
  • 升级react-native版本到0.57.0
  • rm -fr node_modules
  • 升级插件版本react-native-unity-view": "^1.2.1"
  • 在Xcode里Setting "Strip Linked Product" to NO

成功阻止了编译闪退,但发布后被审核告知闪退.来来回回几次后,终于重新测试发现,居然是打包为release IPA file后才开始闪退-_-!!

再次尝试

之后在issue里提问回帖,得到如下方案:

在配置文件里加入

1
2
3
COPY_PHASE_STRIP = YES;
ENABLE_BITCODE = NO;
STRIP_INSTALLED_PRODUCT = NO;

之后在测试机上运行,没有闪退.于是提交审核,发布了版本.之后有用户反馈在IPHONE XS Max上闪退 -_-!!!

最后的尝试

之后继续回帖,在 JanOwiesniak和mtostenson 的建议下,进行如下改动:

  • using XCodes new build system or the legacy build system
  • Reinstall node_modues
  • Update Unity from 2018.2.14f1 to 2018.3.6f1
  • Build UnityExport
  • Patch UnityExport jiulongw/swift-unity#120 (comment) #79 (comment)
  • Update react-native-unity-view to 1.3.3
  • Update react-native to 0.57+
  • Patch react-native moduleNames() (#79 (comment)
  • Add AVKit.framework in Xcode
最终成功解决iphone xs max 12.1兼容
1…345…16
peterfei

peterfei

peterfei|技术|上主是我的牧者

77 日志
14 分类
62 标签
RSS
github
© 2023 peterfei
由 Hexo 强力驱动
主题 - NexT.Mist