Docker-Compose Overwriting Dockerfile Data
Photo by Bernard Hermant on Unsplash
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 nodejs2 FROM node:lts-alpine34 # install aurelia-cli to build the app & http-server to serve static contents5 RUN npm i -g aurelia-cli@0.16.067 # set working directory to app8 # henceforth all commands will run inside this folder9 WORKDIR /app1011 # copy package.json related files first and install all required dependencies12 COPY ./frontend/package*.json ./13 RUN npm install
This was my docker-compose file:
1version: '3.9'23services:4 backend:5 build:6 context: .7 dockerfile: Dockerfile.backend8 command: python api.py9 volumes:10 - ./backend:/backend11 ports:12 - '8085:8085'13 frontend:14 build:15 context: .16 dockerfile: Dockerfile.frontend17 command: au run --watch18 volumes:19 - ./frontend:/app20 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.frontend5 command: au run --watch6 volumes:7 - ./frontend:/app8 - /app/node_modules9 ports:10 - '3001:3001'11 - '9000:9000'