Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse image built by one service in another service

Let's say I have this project structure:

proj/
├── docker
│   └── myservice
│       └── Dockerfile
└── docker-compose.yml

And this is my docker-compose.yml:

version: '3'

services:

  master:
      build: docker/myservice

  slave:
      image: proj_master
      depends_on: master

I want the master service to create an image, which will be used by the master and the slave services (with different parameters, not shown here). By trial and error I have found out that the slave must refer to the image proj_master.

  • Where is this documented?
  • Why do I need to make a reference to the proj? Usually a docker composer file is agnostic related to where it is located ...

2 Answers

Docker Compose builds your image with the name proj_master, beacuse you did not specify an image name under your master service in the Compose file.

You have a build section, so Docker Compose will build the image and give it a name based on your <directory_name_where_you_run_compose>_<service_name>:latest. I did not find this in the documentation, but tried with one of my projects, and it's in line with what you experienced.

You can fix your project by specifying the image name in your Compose file and using the same image for both services:

version: '3'


services:

  master:
      build: docker/myservice
      image: username/masterimage:version


  slave:
      image: username/masterimage:version
      depends_on: master
like image 97
takacsmark Avatar answered Sep 04 '25 03:09

takacsmark


This feature is called extension fields.

You can just link your slaves to your master.

django_project: 
  &django_project
  image: python:3.7.6-alpine
   command: ....  

django_project_task1:
  <<: *django_project
  command: /start-task1.sh 

django_project_task2:
  <<: *django_project
  command: /start-task2.sh 

Now the all share the same source but use different command to start.

Also, you have to understand one more thing.

Since Docker uses "layers" your Dockerfile is not going to be recompiled for every "sub-proccess" and volume size is going to be shrinked.

There is a perfect article on this topic

Also check out this article about running multiple process in one container.

Cool hack, huh?

like image 29
Alexander Paul Wansiedler Avatar answered Sep 04 '25 05:09

Alexander Paul Wansiedler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!