创建一个docker容器

  • Post author:
  • Post category:其他


根据第一节,把docker安装完毕并学习了基本操作之后,我们来学习构建一个docker应用程序

要创建一个便携的镜像,首先需要创建一个叫做Dockerfile的文件,这个文件定义了你要创建的容器所需要的环境配置。由于这个环境是虚拟化的,所以与外部环境隔离,因此需要将你所需要用到的端口映射到外部,并具体说明这个环境中需要什么样的配置,这样做之后,就可以通过Dickerfile构建应用程序,并且运行到任何地方。

接下来逐步说明docker应用程序的创建过程。

创建一个空目录,并在此目录中创建Dockerfile文件,定义应用程序的环境,配置如下:

# Use an official Python runtime as a base 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 NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]

阅读配置信息可以看出,我们还需要创建requirements.txt和app.py文件,文件内容分别是:

requirements.txt

Flask

Redis

这里的Flask和Redis分别是需要给Python安装的库,因为在运行时需要这两个库的支持。

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)

这个app.py做了两个事情,第一,启动Flask服务,第二链接redis服务器。

文件准备完毕,我们就开始进行应用程序的构建了,在创建的目录下运行命令:

docker build -t xxxx .

xxxx表示将要生成的容器名称

build image

注意:在容器名称中输入大写字母直接报错,意思是不能使用大写字母,将大写字母改成小写即可。

这里写图片描述

通过运行过程我们可以看到,写在Dockerfile的配置全部运行完成,则表示容器创建成功。

接下来,我们来看一下创建的容器放在了哪里,docker images 一下:

查看image

可以看到,已经生成在了images列表中,然后,我们来对该容器进行测试:

使用docker run -p 9999:80 my-helloworld 来运行容器,其中 -p 表示我们要使用外部端口来映射容器的80端口

端口映射

在浏览器中输入

http://192.168.83.129:9999

,当我们看到如下页面时,表示我们的容器已经生成完毕,可以发布和使用了。

查看部署页面

这里的报无法连接Redis的错误是因为我们没有安装Redis数据库,而仅仅安装了Python的redis库的原因。在服务端,我们看到访问记录如下:

服务端记录

当然我们也可以在后台运行我们的应用程序,只需要加上-d参数即可,即:

docker run -d -p 9999:80 my-helloworld

如果要关闭应用,运行 docker stop imageid

如果要上传此容器到Docker Hub,只需参考初识docker部分,上传之后,就可以在任何安装docker的机器上运行docker run -pxxxx:80 xxxx/xxxx来从docker库中拉取xxxx/xxxx的镜像了。

一些常用命令:

docker build -t friendlyname .  # Create image using this directory's Dockerfile
docker run -p 4000:80 friendlyname  # Run "friendlyname" mapping port 4000 to 80
docker run -d -p 4000:80 friendlyname         # Same thing, but in detached mode
docker ps                                 # See a list of all running containers
docker stop <hash>                     # Gracefully stop the specified container
docker ps -a           # See a list of all containers, even the ones not running
docker kill <hash>                   # Force shutdown of the specified container
docker rm <hash>              # Remove the specified container from this machine
docker rm $(docker ps -a -q)           # Remove all containers from this machine

docker images -a                               # Show all images on this machine
docker rmi <imagename>            # Remove the specified image from this machine
docker rmi $(docker images -q)             # Remove all images from this machine
docker login             # Log in this CLI session using your Docker credentials
docker tag <image> username/repository:tag  # Tag <image> for upload to registry
docker push username/repository:tag            # Upload tagged image to registry
docker run username/repository:tag                   # Run image from a registry