user1717828
user1717828

Reputation: 7223

Share folder and Python file between Docker images using Docker Compose

I would like different Docker projects for my closely related projects server_1 and server_2 to live in one folder that I can build/deploy simultaneously using Docker Compose.

Example project directory:

.
├── common_files
│   ├── grpc_pb2_grpc.py
│   ├── grpc_pb2.py
│   └── grpc.proto
├── docker-compose.yml
├── flaskui
│   ├── Dockerfile
│   └── flaskui.py
├── server_1
│   ├── Dockerfile
│   └── server_1.py
├── server_2
│   ├── Dockerfile
│   └── server_2.py
└── server_base.py

Two questions I am hoping have one common solution:

  1. How can I make it so I only have the common dependency common_files/ in only one place?
  2. How can I use the common code server_base.py in both server projects?

I've tried importing using relative directories in my project Python scripts, like from ..common_files import grpc_pb2, but I get ValueError: attempted relative import beyond top-level package.

I've considered using read_only volume mounting in docker-compose.yml, but that doesn't explain how to reference the common_files from within a project file like flaskui/Dockerfile.

Upvotes: 1

Views: 1635

Answers (1)

gravetii
gravetii

Reputation: 9644

You need to mount your local directory that contains the grpc files and server_base.py as a volume in your server_1 and server_2 containers. That way, there is a single source of truth (your local directory) and you can use them from both your containers.

You can add the volumes definition in your docker-compose.yml file for your containers. Here's a bare-bones compose file I created for your use-case:

version: "3"

services:
  server_1:
    image: tutum/hello-world
    ports:
      - "8080:8080"
    container_name: server_1
    volumes:
      - ./common_files:/common_files

  server_2:
    image: tutum/hello-world
    ports:
      - "8081:8081"
    container_name: server_2
    volumes:
      - ./common_files:/common_files

common_files is the folder in your local directory that has the server_base.py along with the grpc files which you want to mount as volumes to your containers which need to use them. These are called host volumes since you are mounting your local files from your host as volumes for your containers.

With this setup, when you exec into server_1, you can see that there's a common_files folder sitting in the / directory. Similarly for server_2.

You can exec into server_1 using docker-compose exec server_1 /bin/sh

You can also read up more on the documentation for Docker volumes.

Upvotes: 1

Related Questions