Dockerfile Templates for Node.js
This guide helps you create appropriate Dockerfiles for Node.js projects.
Key Points for All Dockerfiles
- Using official Node.js images
- Creating a non-root user for enhanced security
- Using environment variables for greater flexibility
- Optimization for various Node.js applications
FROM node:$node_version
ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o app && \
useradd -g $GID -u $UID -mr -d /home/app -o -s /bin/bash app
WORKDIR /home/app
COPY --chown=app:app package*.json ./
RUN npm install
COPY --chown=app:app . .
USER app
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE $PORT
CMD [ "npm", "start" ]
info
- This Dockerfile is designed for a standard Node.js application.
- Uses a non-root user to run the application.
- Dependencies are installed before copying the main code to better utilize Docker cache.
- Environment variables are considered for various configurations.
caution
- Replace
$node_version
with your desired Node.js version. - Adjust the
CMD
command based on project needs (e.g.,npm start
,node index.js
, etc.). - If additional system packages are needed, add them before
npm install
.
Building and Running the Dockerfile
To build the Dockerfile and create an image:
docker build -t [ProjectName] .
- -t: Giving a specific tag and name for the project
And then to run it:
docker run -p outport:inport[3000] --name=container-name -d [ProjectName]
- -p: Specify port for running the project
- outport: External port
- inport: Internal project port specified in the Dockerfile
- --name: Set container name
- -d: Run container in detached mode
caution
-
Security:
- Always use the latest stable Node.js versions
- Avoid installing unnecessary packages
- Always use a non-root user
-
Optimization:
- Use .dockerignore to exclude unnecessary files
- Use
npm ci
instead ofnpm install
in production - Reduce final image size by using alpine images
-
Testing: Always test your Docker image before deploying to production.