简单代码:
from flask import Flask app=Flask(__name__) @app.route(‘/‘) def hello(): return ‘hello world‘ if __name__ == ‘__main__‘: app.run()
app.py
FROM python:3.6 LABEL maintainer="FELIX [email protected]" RUN pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple flask COPY app.py /app/ WORKDIR /app EXPOSE 5000 CMD ["python3","app.py"]
Dockerfile
然后执行命令:
docker build -t felix/flask-demo . 打包docker image ls 查看docker run -d felix/flask-demo 运行,-d参数为在后台运行docker ps 查看运行的程序
多模块代码--redis模块和python
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/8/9 14:14 from flask import Flask from redis import Redis import os import socket app = Flask(__name__) redis = Redis(host=os.environ.get(‘REDIS_HOST‘, ‘127.0.0.1‘), port=6379) @app.route(‘/‘) def index(): redis.incr(‘hits‘) return ‘Hello Container World! I have been seen {} times and my hostname is {}.\n‘.format(str(redis.get(‘hits‘)),socket.gethostname()) if __name__ == ‘__main__‘: app.run(host=‘0.0.0.0‘, port=5000, debug=True)
app.py
FROM python:3.6 LABEL maintainer="FELIX [email protected]" RUN pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple flask redis COPY app.py /app/ WORKDIR /app EXPOSE 5000 CMD ["python3","app.py"]
Dockerfile
可以看到上面的dockerfile并没有redis模块的安装,通常来说一个模块放在一个容器里面
然后执行命令:
docker run -d --name redis redis 下载并安装运行redis模块容器 docker build -t felix/flask-redis-demo . 将上面的Dockerfile打包成image docker run -d -p 5000:5000 --link redis --name flask-redis -e REDIS_HOST=redis felix/flask-redis-demo 运行并传递参数以及端口,环境变量 -p指定端口映射,--link指定连接到的容器,之后访问可以直接用别名,-e表示传递参数执行上面代码之后就能通过宿主机访问127.0.0.1:5000
原文地址:https://www.cnblogs.com/felixwang2/p/9444322.html
时间: 2024-10-29 19:35:37