Docker Compose: Sharing code between services

Sanjay Guruprasad
2 min readAug 3, 2017
The container life is amaze

I had a situation where I had some common code I wanted to share across two docker containers. This couldn’t be done earlier, but docker-compose now allows you to specify build contexts and dockerfiles at a service level, making this super easy! Thought I’d document the steps here.

The folder structure

One folder + Dockerfile per service and the folder contains the parts of the code that are unique. For example, let’s say I had a simple project with two scrapers that I wanted to run in separate containers and a postgres database that they both wrote to. Let’s say the two scrapers shared a bunch of functions and these functions resided in common_lib/scripts.py.

+-- docker_project
| +-- docker-compose.yml
| +-- scraper_1
| +-- Dockerfile
| +-- scraper_1.py
| +-- scraper_2
| +-- Dockerfile
| +-- scraper_2.py
| +-- common_lib
| +-- scripts.py

There’s only one simple rule with docker-compose — a container cannot access anything outside its build context. So you can’t access the common_lib folder and copy it over to your container if your build context is set to docker_project/scraper_1. Instead, we must set the build context for each of the services to be the docker_project folder, and then specify…

--

--

Sanjay Guruprasad

I love to code, cook and watch movies. Building Rune 🚀 Previously Social Networks @ MIT, Physics @ IIT Madras. https://sanjay.cc