IPO
IPO

Reputation: 835

Convert a docker run command to docker-compose - setting directory dependency

I have two docker run commands - the second container need to be ran in a folder created by the first. As in below

docker run -v $(pwd):/projects \
             -w /projects \
             gcr.io/base-project/mainmyoh:v1 init myprojectname

cd myprojectname 

The above myprojectname folder was created by the first container. I need to run the second container in this folder as below.

docker run -v $(pwd):/project \
            -w /project \
            -p 3000:3000 \
            gcr.io/base-project/myoh:v1        

Here is the docker-compose file I have so far:

version: '3.3'
services:
    firstim:
        volumes:
            - '$(pwd):/projects'
        restart: always
        working_dir: /project
        image: gcr.io/base-project/mainmyoh:v1
        command: 'init myprojectname'

    secondim:
        image: gcr.io/base-project/myoh:v1
        working_dir: /project
        volumes:
        - '$(pwd):/projects'
        ports:
        - 3000:3000

What need to change to achieve this.

Upvotes: 0

Views: 801

Answers (2)

Yogarine
Yogarine

Reputation: 415

You can make the two services use a shared named volume:

version: '3.3'
services:
    firstim:
        volumes:
          - '.:/projects'
          - 'my-project-volume:/projects/myprojectname'
        restart: always
        working_dir: /project
        image: gcr.io/base-project/mainmyoh:v1
        command: 'init myprojectname'

    secondim:
        image: gcr.io/base-project/myoh:v1
        working_dir: /project
        volumes:
          - 'my-project-volume:/projects'
        ports:
          - 3000:3000

volumes:
    my-project-volume:

Also, just an observation: in your example the working_dir: references /project while the volumes point to /projects. I assume this is a typo and this might be something you want to fix.

Upvotes: 2

David Maze
David Maze

Reputation: 158868

You can build a custom image that does this required setup for you. When secondim runs, you want the current working directory to be /project, you want the current directory's code to be embedded there, and you want the init command to have run. That's easy to express in Dockerfile syntax:

FROM gcr.io/base-project/mainmyoh:v1
WORKDIR /project
COPY . .
RUN init myprojectname
CMD whatever should be run to start the real project

Then you can tell Compose to build it for you:

version: '3.5'
services:
  # no build-only first image
  secondim:
    build: .
    image: gcr.io/base-project/mainmyoh:v1
    ports:
      - '3000:3000'

In another question you ask about running a similar setup in Kubernetes. This Dockerfile-based setup can translate directly into a Kubernetes Deployment/Service, without worrying about questions like "what kind of volume do I need to use" or "how do I copy the code into the cluster separately from the image".

Upvotes: 0

Related Questions