Docker 入门

Docker是.......

快速上手

1. 安装

以MacOS为例, 其他操作系统的docker安装与运行,请绕道至 Docker官网

下载地址:

MacOS的Docker安装包地址

然后dmg文件安装即可.

运行

和其他软件一样, 运行Docker即可

2. 登入账号

在 docker.io 上面注册你个人的账号, 用于创建同步你个人的容器镜像

回到本机, 我们使用命令行登入即可

docker login
## 后续根据提示,输入你的账号密码登入

3. 简单命令

官方给出了一个示例命令

docker run hello-world

运行结果如下:

控制打印了一段说明文字

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://cloud.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/

大致介绍了 docker run xxxx 命令后,docker内部帮我完成的后续工作

4. 创建容器 (Container)

官网给出了一个docker运行python的web应用的demo. 详细步骤如下:

1. 创建一个工作目录

# 我根据个人代码习惯, 创建了如下目录, (其实我们只需要一个新的有操作权限的目录空间)
mkdir -p ~/code/docker/demo-python
cd ~/code/docker/demo-python

2. 创建Dockerfile文件

# 切换到工作目录
cd ~/code/docker/demo-python

# 创建 Dockerfile
touch Dockerfile

vim Dockerfile
# 编辑文件 Dockerfile 内容如下
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 --trusted-host pypi.python.org -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"]

3. 增加python栈的Web服务代码

在工作目录下创建 requirements.txtapp.py

requirements.txt
Flask
Redis
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 = "cannot connect to Redis, counter disabled"

    html = "

Hello {name}!

" \ "Hostname: {hostname}
" \ "Visits: {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)

4. 构建

# -t 参数为 指定tagname
docker build -t demopython .

# 查看刚构建的镜像
docker images

5. 运行

# -p 参数: 使用本机4000端口映射容器中80端口服务
docker run -p 4000:80 demopython

6. 访问服务

打开浏览器访问服务 http://localhost:4000