1.创建空目录
$ cd /home/xm6f/dev $ mkdir myapp$ cd myapp/
2.vim Dockerfile,内容如下:
## 一个基础的 python 运行环境FROM python## 设置工作目录WORKDIR /app## 将当前系统文件夹内容复制到容器的 app 目录ADD . /app## 安装必要的依赖包RUN pip install -r softwares.txt## 开放端口,供容器外访问EXPOSE 80EXPOSE 3088EXPOSE 8080EXPOSE 8066## 定义环境变量ENV NAME HELLO## 运行命令CMD ["python","app.py"]
3.安装依赖
vim softwares.txt,内容如下:
4.vim app.py,内容如下:
from flask import Flaskfrom redis import Redis, RedisErrorimport osimport socket# Connect to Redisredis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)app = Flask(__name__)@app.route("/")def hello(): try: visits = redis.incr("counter") except RedisError: visits = "<i>cannot connect to Redis, counter disabled</i>" html = "<h3>Hello {name}!</h3>" / "<b>Hostname:</b> {hostname}<br/>" / "<b>Visits:</b> {visits}" return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
5.编译
$ docker build -t myfirstapp .
6.查看新生成了一个image
$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEmyfirstapp latest 01ea1129a831 2 hours ago 699MB
7.启动image
$ docker run -p 4000:80 myfirstapp
也可以放在后台运行:
$ docker run -d -p 4000:80 myfirstapp
8.访问服务
# curl http://localhost:4000<h3>Hello world!</h3><b>Hostname:</b> a6655d0d7e74<br/><b>Visits:</b> <i>cannot connect to Redis, counter disabled</i>
或者浏览器访问服务:http://192.168.1.160:4000
9.查看当前运行的镜像
$ docker psCONTAINER ID MAGE COMMAND CREATED STATUS PORTS NAMES2db45cab2bb4 myfirstapp "python app.py" 2 minutes ago Up 2 minutes 0.0.0.0:4000->80/tcp elastic_wilson
10.停止镜像
$ docker stop 2db45cab2bb4
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。
注:相关教程知识阅读请移步到服务器教程频道。