环境准备
1.安装docker,并启动
yum install docker
service docker start
2.获取主机名: abcdef
hostname
最终文件目录:
ls
Dockerfile app.py requirements.txt
创建镜像
1.创建空目录
mkdir myapp
cd myapp/
2.vim Dockerfile
# Use an official Python runtime as a parent image
FROM python:2.7-slim
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV abcdef World
# Run app.py when the container launches
CMD ["python", "app.py"]
3.安装依赖
vim requirements.txt
Flask
Redis
pip install -r requirements.txt
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 f0f4731de261 10 seconds ago 195.4 MB
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>
9.查看当前运行的镜像
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a6655d0d7e74 myfirstapp "python app.py" 25 minutes ago Up 25 minutes 0.0.0.0:4000->80/tcp distracted_liskov
10.停止镜像
# docker stop a6655d0d7e74
a6655d0d7e74
发布镜像
1.登录docker
docker login
2.标记镜像
docker tag myfirstapp wxmgcs/firstapp:part2
查看结果
# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
wxmgcs/firstapp part2 f0f4731de261 3 minutes ago 195.4 MB
myfirstapp latest f0f4731de261 3 minutes ago 195.4 MB
3.发布镜像
docker push wxmgcs/firstapp:part2