Prod NodeJS Docker Config

Published on
2 mins read
––– views
Dockerfile
# Multistage production docker configuration for NodeJs applications
# ===========Build stage
FROM node:16-alpine As builder
ENV NODE_ENV build
WORKDIR /usr/src/app
COPY package*.json ./
## Install build toolchain, install node deps and compile native add-ons
RUN apk add --no-cache python3 make g++
RUN npm ci --only=builder
COPY . .
RUN npm run build
# ===========Production stage
FROM node:16-alpine As production
# Setup user to avoid running as root
USER node
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
# The following line assumes the node library or framework your using will output the
# built js files inside dist folder. If not you can change the following line
COPY --from=builder /usr/src/app/dist ./dist
# Again the following line assumes that the entry point to your application is main.js
# and you use below command to run the production build
CMD ["node", "dist/main.js"]

Usage

1. Setup your environment

First you should have build script inside your package.json file that builds your node application and outputs the built production build somewhere

2. Customize the docker configuration

Depending on your needs you should change the lines highlighted above. If you have different script in your package.json file alter line 19. If your application outputs the production build to a directory other than dist change line 40. Also change line 44 to reflect the command you use to run your production build application

3. Build your docker image

To build your docker container run the following command with your own image name

docker build -f Dockerfile.prod -t <image-name> .

4. Run the built docker container

To run the docker image you just built run

docker run <image-name>

If there is environment variable you want to inject you can run

docker run --env <image-name>