christophe31
christophe31

Reputation: 6467

docker-compose build build each Dockerfile as many time as they are used

I have a docker-compose.yml with multiple services using same Dockerfile (django, celery, and many more) When I use docker-compose build, it build my container multiple times.

It make my "apply changes and restart" process costly. Is there a good way to build the Dockerfile only once? Sould I build only one container and hope it updates all?

In my case I have 5 instance of a Dockerfile simply using a different commands, different volumes…

Upvotes: 2

Views: 7943

Answers (1)

Ayushya
Ayushya

Reputation: 10447

Using --build flag along with docker-compose up makes docker to build all containers. If you want to build only once then you can name the image which is built in one service and for other services, instead of using dockerfile, you can use that newly built image.

version: '3'
services:

  wordpress-site-1:
    image: wordpress:custom
    build:
      context: ./wordpress
      dockerfile: wordpress.dockerfile
    container_name: wordpress-site-1
    links:
      - mysql-database
    depends_on:
      - mysql-database
    ports:
      - 8080:80

  wordpress-site-2:
    image: wordpress:custom
    container_name: wordpress-site-2
    links:
      - mysql-database
    depends_on:
      - mysql-database
      - wordpress-site-1
    ports:
      - 8888:80

Note: build and image are used in first service and only image is used in the second service.

This is sample usage which generates two wordpress containers, one of which is built from the dockerfile which is specified in context and names the generated image as wordpress:custom and other is built from the image wordpress:custom. The container name is different but the image used is same in both the services. One service builds the image using build context and other uses that image. Being at safe side, you may remove any previous wordpress:custom image. So that wordpress-site-2 does not use cached image.

Edit 1: Extended answer to show how two containers are built using same image. Same container_name cannot be used.

Upvotes: 2

Related Questions