插件窝 干货文章 Docker平时怎么使用的

Docker平时怎么使用的

Docker 容器 bash nginx 263    来源:    2025-04-28

Docker 是一个强大的容器化平台,可以帮助你快速部署、运行和管理应用程序。以下是一些常见的 Docker 使用场景和基本操作:


1. 安装 Docker

  • Linux (Ubuntu/Debian): bash sudo apt update sudo apt install docker.io sudo systemctl start docker sudo systemctl enable docker
  • Mac/Windows:
    • 下载 Docker Desktop(官网)并安装。

2. 基本 Docker 命令

镜像管理

  • 拉取镜像(如 nginx): bash docker pull nginx
  • 查看本地镜像: bash docker images
  • 删除镜像: bash docker rmi <镜像ID>

容器管理

  • 运行容器(以 nginx 为例): bash docker run -d -p 8080:80 --name my-nginx nginx
    • -d:后台运行
    • -p 8080:80:将主机的 8080 端口映射到容器的 80 端口
    • --name:指定容器名称
  • 查看运行中的容器: bash docker ps
  • 查看所有容器(包括已停止的): bash docker ps -a
  • 停止/启动容器: bash docker stop my-nginx docker start my-nginx
  • 进入容器(调试): bash docker exec -it my-nginx /bin/bash
  • 删除容器: bash docker rm <容器ID>

日志与监控

  • 查看容器日志: bash docker logs my-nginx
  • 查看资源占用: bash docker stats

3. 构建自定义镜像(Dockerfile)

  1. 创建 Dockerfiledockerfile FROM ubuntu:20.04 RUN apt update && apt install -y python3 COPY ./app /app CMD ["python3", "/app/main.py"]
  2. 构建镜像: bash docker build -t my-python-app .
  3. 运行容器: bash docker run -d my-python-app

4. 数据卷(持久化存储)

  • 挂载主机目录到容器: bash docker run -v /host/path:/container/path nginx
  • 使用命名卷: bash docker volume create my-vol docker run -v my-vol:/container/path nginx

5. 网络管理

  • 查看网络: bash docker network ls
  • 创建自定义网络: bash docker network create my-net
  • 运行容器并加入网络: bash docker run --network=my-net nginx

6. Docker Compose(多容器编排)

  1. 创建 docker-compose.ymlyaml version: "3" services: web: image: nginx ports: - "8080:80" db: image: mysql environment: MYSQL_ROOT_PASSWORD: 123456
  2. 启动服务: bash docker-compose up -d
  3. 停止服务: bash docker-compose down

7. 常见使用场景

  1. 开发环境隔离:每个项目使用独立的容器(如 Python、Node.js)。
  2. 微服务部署:每个服务运行在单独的容器中。
  3. CI/CD 流水线:在容器中运行测试和构建。
  4. 快速搭建服务:如 MySQL、Redis、Elasticsearch 等。

8. 注意事项

  • 清理无用数据bash docker system prune
  • 安全:避免以 root 权限运行容器。
  • 资源限制:使用 --memory--cpus 限制容器资源。

通过 Docker,你可以实现快速部署、环境一致性和高效的资源利用。如果需要更高级的功能(如 Kubernetes 编排),可以进一步学习 Docker Swarm 或 Kubernetes。