【Docker系列】docker-compose 服务更新

云凌
2023-12-01

请先了解docker-compose基础理论和命令:《Docker Compose基础篇》

服务更新

当你修改代码后,直接使用docker-compose up 时候就是start启动,没有重新部署。

手动更新服务:docker-compose build

version: "3.8"

services:
  flask-demo:
    build: 
      context: ./flask # 指定的目录
      dockerfile: Dockerfile-flask.txt  # 自定义Dockerfile文件名称
    environment:
      - REDIS_HOST=redis-server
    networks:
      - demo-network
    ports:
      - 8080:5000

  redis-server:
    image: redis:latest
    networks:
      - demo-network

networks:
  demo-network:

或者
docker-compose up -d --build 虽然已经启动,也可以继续输入这个命令。先会查看镜像,要需要build的地方重新构建。最后创建修改后的服务。

增加新的容器

version: "3.8"

services:
  flask-demo:
    build: 
      context: ./flask # 指定的目录
      dockerfile: Dockerfile-flask.txt  # 自定义Dockerfile文件名称
    environment:
      - REDIS_HOST=redis-server
    networks:
      - demo-network
    ports:
      - 8080:5000

  redis-server:
    image: redis:latest
    networks:
      - demo-network
  
  # 添加容器
  busybox:
    image: busybox:latest
    command: sh -c "while true; do sleep 3600; done"
    networks: 
      - demo-network

networks:
  demo-network:

输入:

PS F:\docker> docker-compose -f .\docker-compose.yml up -d
Pulling busybox (busybox:latest)...
latest: Pulling from library/busybox
5cc84ad355aa: Pull complete
Digest: sha256:5acba83a746c7608ed544dc1533b87c737a0b0fb730301639a0179f9344b1678
Status: Downloaded newer image for busybox:latest
Starting docker_redis-server_1 ... done
Recreating docker_flask-demo_1 ... done
Creating docker_busybox_1      ... done
PS F:\docker>

删除多余的容器

version: "3.8"

services:
  flask-demo:
    build: 
      context: ./flask # 指定的目录
      dockerfile: Dockerfile-flask.txt  # 自定义Dockerfile文件名称
    environment:
      - REDIS_HOST=redis-server
    networks:
      - demo-network
    ports:
      - 8080:5000

  redis-server:
    image: redis:latest
    networks:
      - demo-network
  
  # 删除容器

networks:
  demo-network:

直接执行docker-compose up -d,会提示出现一个“孤儿容器”

PS F:\docker> docker-compose -f .\docker-compose.yml up -d
WARNING: Found orphan containers (docker_busybox_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
docker_flask-demo_1 is up-to-date
docker_redis-server_1 is up-to-date
PS F:\docker>

正确的删除多余容器的写法:添加 --remove-orphans

PS F:\docker> docker-compose -f .\docker-compose.yml up -d --remove-orphans
Removing orphan container "docker_busybox_1"
docker_redis-server_1 is up-to-date
docker_flask-demo_1 is up-to-date
PS F:\docker>

重启服务

重启命令:docker-compose restart

PS F:\docker> docker-compose -f .\docker-compose.yml restart
Restarting docker_flask-demo_1   ... done
Restarting docker_redis-server_1 ... done
PS F:\docker>
 类似资料: