Docker
环境安装
卸载旧版本残留
1
| sudo apt-get remove docker.io docker-engine
|
- 下载并安装密钥
1
| curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/debian/gpg | sudo apt-key add -
|
- 检查是否安装成功
1
| sudo apt-key fingerprint 0EBFCD88
|
- 在source.list中添加docker-ce的软件源
1 2 3
| sudo deepin-editor /etc/apt/sources.list.d/docker.list
deb [arch=amd64] https://mirrors.ustc.edu.cn/docker-ce/linux/debian buster stable
|
注意: 使用 cat /etc/debian_version 查看自己的 debain 版本。
- 更新仓库
- 安装docker
1
| sudo apt install docker-ce docker-ce-cli containerd.io
|
验证
管理启动项
1 2 3 4 5 6
| sudo apt install chkconfig
sudo chkconfig
sudo chkconfig --del docker
|
- Rootless 配置
1 2
| sudo usermod -aG docker $USER reboot
|
常用命令
拷贝文件夹
1
| docker cp <container>:<container-dir> <local-dir>
|
Docker Compose
环境安装
- 下载二进制包
https://github.com/docker/compose/releases
- 添加权限并移动到/usr/local/bin下
1 2
| sudo chmod 755 docker-compose-linux-x86_64 sudo mv docker-compose-linux-x86_64 /usr/local/bin/docker-compose
|
- 验证
简单示例
1. 定义应用依赖
使用一个简单的程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import time
import redis from flask import Flask
app = Flask(__name__) cache = redis.Redis(host='redis', port=6379)
def get_hit_count(): retries = 5 while True: try: return cache.incr('hits') except redis.exceptions.ConnectionError as exc: if retries == 0: raise exc retries -= 1 time.sleep(0.5)
@app.route('/') def hello(): count = get_hit_count() return 'Hello World! I have been seen {} times.\n'.format(count)
|
并提供其软件包requirements.txt
2. 定义一个Dockerfile
1 2 3 4 5 6 7 8 9 10 11
| FROM python:3.7-alpine WORKDIR /code ENV FLASK_APP=app.py ENV FLASK_RUN_HOST=0.0.0.0 RUN apk add --no-cache gcc musl-dev linux-headers COPY requirements.txt requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 COPY . . CMD ["flask", "run"]
|
3. 定义一个compose文件
1 2 3 4 5 6 7
| services: web: build: . ports: - "8000:5000" redis: image: "redis:alpine"
|
4. 构建运行
运行docker compose up
停止运行docker compose down
5. compose文件添加挂载
重新编辑一下compose文件
1 2 3 4 5 6 7 8 9 10 11
| services: web: build: . ports: - "8000:5000" volumes: - .:/code environment: FLASK_DEBUG: "true" redis: image: "redis:alpine"
|
6. 重新构建
7. 应用更新
由于在上面的步骤中,我们将应用程序的代码与容器进行挂载,因此,当我们现在对源代码进行修改时,容器里头的代码也会跟着修改
1
| return 'Hello from Docker! I have been seen {} times.\n'.format(count)
|