user12384512
user12384512

Reputation: 3401

How to change source code without rebuilding image in Docker?

What is the best practice to use Docker container for dev/prod.

Let's say I want my changes to be applied automatically during development without rebuilding and restarting images. As far as I understand I can inject volume for this when running container.

docker run -v `pwd`/src:/src --rm -it username/node-web-app0

Where pwd/src stands for the directory source code. It's working fine so far.

But how to delivery code to production? I think it worse to keep code along with binaries into the docker container. Do I need to create another similar docker file which will use COPY instead? Or it's better to deploy source-code separately like for dev-mode and mount it to docker.

Upvotes: 7

Views: 9924

Answers (1)

Ignacio Millán
Ignacio Millán

Reputation: 8026

The best practice is to build a new docker image for every version of your code. That has many advantages in production environments as faster deployments, independence from other systems, easier rollbacks, exportability, etc.

It is possible to do it within the same Dockerfile, using multi-stage builds.

The following is a simple example for a NodeJS app:

FROM node:10 as dev
WORKDIR /src
CMD ["myapp.js"]

FROM node:10
COPY package.json .
RUN npm install
COPY . .

Note that this Dockerfile is only for demo purposes, it can be improved in many ways.

When working on dev environment use the following commands to build the base image and run your code with a mounted folder:

docker build --target dev -t username/node-web-app0 .
docker run -v `pwd`/src:/src --rm -it username/node-web-app0

And when you're ready for production, just exec docker run without the --target argument to build the full image, that contains the code:

docker build -t username/node-web-app0:v0.1 .
docker push username/node-web-app0:v0.1 

Upvotes: 8

Related Questions