docker Dockerfile文件制作自己的镜像的方法

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 80
EXPOSE 3088
EXPOSE 8080
EXPOSE 8066
## 定义环境变量
ENV NAME HELLO
## 运行命令
CMD ["python","app.py"]

3.安装依赖

vim softwares.txt,内容如下:

Flask
Redis

4.vim app.py,内容如下:

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.编译

$ docker build -t myfirstapp .

6.查看新生成了一个image

$ docker images
REPOSITORY     TAG     IMAGE ID   CREATED    SIZE
myfirstapp     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 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.停止镜像

$ docker stop 2db45cab2bb4

相关推荐