简单感受docker

docker是近两年几乎所有互联网开发者都会直接或者间接接触的东西。加上近期Kubernetes集群的出现,使得这个技术更方便的能够给我们带来帮助。近期serverless概念很火,基于这个原因我打算持续学习容器相关技术。本片会以一个初学者的视角,提供demo与一些常用指令,帮助你感受docker。

安装dockerhub

可以通过 https://hub.docker.com 去下载docker安装包,下载比较慢的话,建议通过迅雷等加速下载。完成注册,打开对应的docker程序即可。

打包docker

结果先行,整体文件目录应该如下

1
2
$ ls
Dockerfile app.py requirements.txt

下面展示每个文件的内容

app.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from flask import Flask
import socket
import os

app = Flask(__name__)

@app.route('/')
def hello():
html = "<h3>Hello {name}!</h3>" \
"<b>Hostname:</b> {hostname}<br/>"
return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname())

if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)

requirements.txt

1
Flask

Dockerfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 使用官方提供的 Python 开发镜像作为基础镜像
FROM python:2.7-slim

# 将工作目录切换为 /app
WORKDIR /app

# 将当前目录下的所有内容复制到 /app 下
ADD . /app

# 使用 pip 命令安装这个应用所需要的依赖
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# 允许外界访问容器的 80 端口
EXPOSE 80

# 设置环境变量
ENV NAME World

# 设置容器进程为:python app.py,即:这个 Python 应用的启动命令
CMD ["python", "app.py"]

下面就可以build这个镜像了

1
$ docker build -t helloworld .

常用指令

  1. 查看本次存放的docker镜像内容

    1
    2
    3
    4
    $ docker image ls

    REPOSITORY TAG IMAGE ID
    helloworld latest 653287cdf998
  2. 启动容器

    1
    $ docker run -p 4000:80 helloworld

    将本地的4000端口映射到容器的80端口。

  3. 给容器打tag

    1
    $ docker tag helloworld YOUR_DOCKERHUB_NAME/helloworld:v1

    此处需要命名成你的docker_hub的名称。比如说我的账号t967012342009

    1
    2
    $ docker tag helloworld t967012342009/helloworld:v1
    $ docker push t967012342009/helloworld:v1
  4. 上传docker

    1
    $ docker push t967012342009/helloworld:v1
  5. 查看当前docker进程

    1
    2
    3
    $ docker ps
    CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
    a84fe34ced0c helloworld "python app.py" 17 minutes ago Up 17 minutes 0.0.0.0:4000->80/tcp nice_spence
  6. 修改内容后提交镜像

    1
    2
    3
    4
    5
    6
    7
    $ docker exec -it a84fe34ced0c /bin/sh
    # 在容器内部新建了一个文件
    root@4ddf4638572d:/app# touch test.txt
    root@4ddf4638572d:/app# exit

    # 将这个新建的文件提交到镜像中保存
    $ docker commit a84fe34ced0c t967012342009/helloworld:v2
  7. 删除某个tag

    1
    $ docker rmi zhaoleipeng/helloworld:v1
# 容器
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×