1.创建空目录
1
2
3
|
$ cd /home/xm6f/dev $ mkdir myapp $ cd myapp/ |
2.vim Dockerfile,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
## 一个基础的 python 运行环境 FROM python ## 设置工作目录 WORKDIR /app ## 将当前系统文件夹内容复制到容器的 app 目录 ADD . /app ## 安装必要的依赖包 RUN pip install -r softwares.txt ## 开放端口,供容器外访问 EXPOSE 80 EXPOSE 3088 EXPOSE 8080 EXPOSE 8066 ## 定义环境变量 ENV NAME HELLO ## 运行命令 CMD [ "python" , "app.py" ] |
3.安装依赖
vim softwares.txt,内容如下:
1
2
|
Flask Redis |
4.vim app.py,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
from flask import Flask from redis import Redis, RedisError import os import socket # Connect to Redis redis = 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.编译
1
|
$ docker build -t myfirstapp . |
6.查看新生成了一个image
1
2
3
|
$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE myfirstapp latest 01ea1129a831 2 hours ago 699MB |
7.启动image
1
|
$ docker run -p 4000:80 myfirstapp |
也可以放在后台运行:
1
|
$ docker run -d -p 4000:80 myfirstapp |
8.访问服务
1
2
|
# 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.查看当前运行的镜像
1
2
3
|
$ docker ps CONTAINER ID MAGE COMMAND CREATED STATUS PORTS NAMES 2db45cab2bb4 myfirstapp "python app.py" 2 minutes ago Up 2 minutes 0.0.0.0:4000->80 /tcp elastic_wilson |
10.停止镜像
1
|
$ docker stop 2db45cab2bb4 |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/linjiqin/p/8669360.html