Dockerfile
# Use an official Python runtime as a parent image
FROM python:2.7
# 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 NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
requirements.txt
Flask
Redia
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)
开始build镜像
sudo docker build -t hello .
会发现上面这样的错误。主要原因是在容器内无法使用网络。
解决办法
可以看到IP4.DNS是202.120.80.2
如果不存在/etc/docker/daemon.json文件,创建一个并编辑为
重启docker服务
sudo service docker restart
如果使用Dockerfile build镜像时需要执行apt-get update操作,可以在Dockerfile中修改容器的镜像源来加速。
RUN sed -i 's/http:\/\/archive.ubuntu.com\/ubuntu\//http:\/\/mirrors.163.com\/ubuntu\//g' /etc/apt/sources.list
重启docker服务之后再次build镜像,可以看到这次没有出现错误
运行容器
发布自己的镜像
首先需要为镜像打上标签,命令的格式为:
sudo docker tag image username/repository:tag
username是在docker hub上注册了的账户名,否则无法push自己的镜像
登录自己的账户
push镜像
然后可以到自己的docker hub上查看push的镜像,也可以通过
docker search指令查找到镜像,但好像刚刚push的镜像还搜不到。