This site runs best with JavaScript enabled.

Docker-Compose Overwriting Dockerfile Data


How to keep docker-compose volumes from overwriting container data.

This little challenge took me longer than I had hoped to figure out, so I figured I would blog about it in case I run into the problem again.

Here was the problem. I dockerized a small coding assignment project. It has a backend server in python/bottle.py and frontend running Aurelia. This is what my frontend dockerfile looked like:

1# use latest version of nodejs
2 FROM node:lts-alpine
3
4 # install aurelia-cli to build the app & http-server to serve static contents
5 RUN npm i -g aurelia-cli@0.16.0
6
7 # set working directory to app
8 # henceforth all commands will run inside this folder
9 WORKDIR /app
10
11 # copy package.json related files first and install all required dependencies
12 COPY ./frontend/package*.json ./
13 RUN npm install

This was my docker-compose file:

1version: '3.9'
2
3services:
4 backend:
5 build:
6 context: .
7 dockerfile: Dockerfile.backend
8 command: python api.py
9 volumes:
10 - ./backend:/backend
11 ports:
12 - '8085:8085'
13 frontend:
14 build:
15 context: .
16 dockerfile: Dockerfile.frontend
17 command: au run --watch
18 volumes:
19 - ./frontend:/app
20 ports:
21 - '3001:3001'
22 - '9000:9000'

The Problem

The dockerfile was installing all the front-end requirements in /app/node_modules. Docker compose was mounting my local ./frontend directory to my container's app directory. For me it was working fine because I had a node_modules directory in my ./frontend directory from running npm install locally. When someone else would check out the project and run docker-compose up they were getting errors because they were missing modules. Their host ./frontend directory did not contain node_modules so it wasn't work.

The Fix

The easiest fix I found was to add the add another volume which essentially keeps the node_modules directory on the server. It is a one-line fix in my docker compose file.

1frontend:
2 build:
3 context: .
4 dockerfile: Dockerfile.frontend
5 command: au run --watch
6 volumes:
7 - ./frontend:/app
8 - /app/node_modules
9 ports:
10 - '3001:3001'
11 - '9000:9000'

Discuss on TwitterEdit post on GitHub

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.

Join the Newsletter



Dustin Davis