Docker是基于 Linux 内核的cgroup、namespace以及 AUFS 类的Union FS 等技术,对进程进行封装隔离,一种操作系统层面的虚拟化技术。Docker中每个容器都基于镜像Image运行,镜像是容器的只读模板,容器是模板的一个实例。镜像是分层结构,一个镜像可以基于另一个镜像创建,最底层的镜像是基础镜像。
安装Docker
brew install --cask --appdir=/Applications docker
查看docker版本
% docker --version
Docker version 20.10.17, build 100c701
查看docker是否安装成功
% docker info
Client:
Context: default
Debug Mode: false
Plugins:
buildx: Docker Buildx (Docker Inc., v0.9.1)
compose: Docker Compose (Docker Inc., v2.10.2)
extension: Manages Docker extensions (Docker Inc., v0.2.9)
sbom: View the packaged-based Software Bill Of Materials (SBOM) for an image (Anchore Inc., 0.6.0)
scan: Docker Scan (Docker Inc., v0.19.0)
创建FastAPI镜像
依赖
% cat requirements.txt
fastapi[standard]>=0.113.0,<0.114.0
pydantic>=2.7.0,<3.0.0
Python代码
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def index():
return "测试容器部署"
目录结构
% tree
.
├── Dockerfile
├── app
│ └── main.py
└── requirements.txt
Dockerfile
% cat Dockerfile
FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
EXPOSE 5000
COPY ./app /code/app
CMD ["fastapi", "run", "app/main.py", "--port", "5000"]
创建镜像
% docker build -t myimage .
[+] Building 54.4s (10/10) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 37B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/python:3.9 4.4s
=> [internal] load build context 0.0s
=> => transferring context: 6.57kB 0.0s
=> [1/5] FROM docker.io/library/python:3.9@sha256:ed8b9dd4e9f89c111f4bd 18.5s
# 查看镜像
% docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
myimage latest 31030096287b 22 minutes ago 1.06GB
运行
% docker run -d --name mycontainer -p 80:5000 myimage
f23deab780852268532e6f820da33df67d6b39ba007db01d6eca2660e345a224
# 查看容器
% docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f23deab78085 myimage "fastapi run app/mai…" 14 minutes ago Up 14 minutes 0.0.0.0:80->5000/tcp mycontainer
# 进入容器
% docker exec -it mycontainer bash
这里docker run
从镜像myimage实例了一个容器,守护模式,命名为mycontainer,容器内部的端口是5000,宿主机的端口是80。
停止和移除容器
# 关闭容器
% docker stop mycontainer
mycontainer
# 启动容器
% docker start mycontainer
mycontainer
# 移除容器
% docker rm mycontainer
mycontainer
配置镜像加速器
{
"registry-mirrors": ["https://docker.wanpeng.top"]
}