Docker Tutorial

22. Docker Node.js | Run and Configure Node.js in Docker

Docker – Setting Node.js

Docker allows you to run Node.js applications in isolated containers, ensuring consistency across development, staging, and production environments. Containerizing Node.js applications simplifies deployment and dependency management.

Dockerizing a Node.js Application

To run a Node.js application in Docker, create a Dockerfile that defines the environment, installs dependencies, and starts the app.


# Dockerfile example for Node.js
FROM node:18

# Set working directory
WORKDIR /app

# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install

# Copy application code
COPY . .

# Expose application port
EXPOSE 3000

# Start the Node.js application
CMD ["node", "index.js"]

Building and Running the Node.js Container


# Build Docker image
docker build -t my-node-app .

# Run container
docker run -d -p 3000:3000 --name node-app my-node-app

# Access app in browser
http://localhost:3000

Using Volumes for Development

During development, you can mount your project directory as a volume to reflect changes instantly without rebuilding the image.


docker run -d -p 3000:3000 -v $(pwd):/app --name node-app my-node-app

Best Practices for Node.js in Docker

  • Use official Node.js Docker images for stability.
  • Keep Docker images small by only copying necessary files.
  • Use npm ci in production for reproducible builds.
  • Expose only required ports and secure your application.
  • Use environment variables to configure application settings.

Conclusion

Docker simplifies running Node.js applications by providing consistent environments and easy deployment. Using best practices, you can build lightweight, scalable, and maintainable Node.js containers for both development and production.

Leave a Reply

Your email address will not be published. Required fields are marked *