Docker Multi-Stage Build

Build from one image, copy to another image

Stage 1

I want my server clean now. Why bother installing Node if it is just for building the app? In the end, Nginx takes care of the server-side.

If you’re lazy like me, this article is for you!

Gone are the days of installing everything on the server. What if you have 10 servers? 20 servers? 40 servers? Installing everything on the servers one by one is a terrible idea.

Nowadays all you have to do is make sure each server already has Docker and Git installed and you’re good to go! The goal is to deploy the latest code — all we have to do is git pull and docker-compose up. Neat!

We’ll compile Vue project into static html and serve it with Nginx. First, you need to have Vue project— clone the hello world vue here .

Next go into the vue-hello-world directory, create new two files and name them Dockerfile and docker-compose.yml. The idea is to use a multi-stage build in Dockerfile.

Stage 1

  • Pull Node image
  • Copy current directory into Node image
  • Install project dependencies
  • Build project

Stage 2

  • Pull Nginx image
  • Copy built project folder from stage 1 to nginx
FROM node AS node
COPY . /root
WORKDIR /root
RUN npm install
RUN npm run build
RUN echo 'BUILD SUCCEEDED'FROM nginx:alpine
COPY --from=node /root/dist /usr/share/nginx/html
RUN echo 'ATTACHED TO NGINX'

In case you’re wondering, npm run build will create a new dist directory containing static html. This static html is what Nginx served.

Then, in docker-compose.yml, we need to write the config to build the image and open a specific port to open to the real world.

version: '3'
services:
app:
build: .
ports:
- "8181:80"
command: 'nginx -g "daemon off;"'

Done! Now we need to test it. Go to vue-hello-world directory and execute this command:

docker-compose up

Docker will now build the image based on the Dockerfile script. Wait a few minutes and your app will be served on localhost:8181.

Finally, when one of your team members commits changes on repo and wants to deploy, all you have to do is git pull and docker-compose up.