Prod NodeJS Docker Config

Production ready docker configuration for nodejs based applications.

Prod NodeJS Docker Config
# Multistage production docker configuration for NodeJs applications

# ===========Build stage
FROM node:16-alpine As builder


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

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"]



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


Customize the docker configu

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


Build your docker image

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

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

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>