首先,我们可以先拉一下底层的image,再把我们的app内容叠上去,从终端机(cmd)打上:
docker pull python
成功的话,可以在介面上看到新的image
再来,我们可以开始写dockerfile(可以放在主程式的旁边):
FROM python:3.9-busterWORKDIR /appCOPY . /appRUN apt-get updateRUN apt-get install nanoRUN pip install -r requirements.txtCMD python3 main.py
可以看到python:3.9-buster为我们刚刚拉到的image名称,再来将目前路径的程式都放到未来container中/app的地方。更新套件及装上nano,未来如果有小地方要修改的话,可以方便我们使用
docker exec -it <container ID> bash
来进行小幅度的修改(注意,小心不要引起git版本的冲突)。
再来藉由requirements.txt来安装想使用的python套件。
在测试阶段可以先使用CMD python3 main.py ,
但是在未来需要正式营运时可以开始使用gunicorn(如果你比较喜欢uwsgi,也可以用这个套件,但是我比较喜欢绿色独角兽)。
CMD nohup gunicorn -w 4 main:app --access-logfile gunicorn_access.txt --error-logfile gunicorn_error.txt -b :5000
nohup可以帮助我们避免关闭session时产生input/output Error,当然你如果都不print东西,也可以避免这个错误。
我们可以将那些路由被接触了,写在gunicorn_access.txt,
错误讯息写在gunicorn_error.txt,
而对外port设定为5000。
进行build image的程序,. 代表现在的路径,代表我们在dockerfile的路径上执行:
docker image build -t <喜欢的image name> .
最后将image run成container,以提供我们的服务:
docker run -p 3000:5000 <喜欢的image name>
对内port为3000,对外为5000,我们可以从localhost:3000来看到我们的服务。