Node.js Docker Containerization

In this tutorial, we’ll explore how to containerize a Node.js application using Docker. Containerization allows for seamless deployment and scaling across different environments.

1. Installing Docker

Before you can containerize your Node.js app, you need to install Docker. Follow the steps below:

# Update apt package index
$ sudo apt update
# Install packages to allow apt to use a repository over HTTPS
$ sudo apt install apt-transport-https ca-certificates curl software-properties-common
# Add Docker’s official GPG key
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
# Set up the stable repository
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
# Install Docker
$ sudo apt update
$ sudo apt install docker-ce

Once installed, check if Docker is running using the command:

$ sudo systemctl status docker

2. Creating a Dockerfile

The next step is to create a `Dockerfile` for your Node.js application. A Dockerfile defines the steps Docker should take to containerize your app.

# Use Node.js official image
FROM node:14
# Set working directory in the container
WORKDIR /usr/src/app
# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install
# Copy the rest of the app
COPY . .
# Expose port for the application
EXPOSE 8080
# Start the app
CMD ["node", "app.js"]

This Dockerfile sets up a Node.js application container. You’ll use it to build your Docker image.

3. Building and Running the Docker Container

Now that you’ve created your Dockerfile, you can build the image and run the container:

# Build the Docker image
$ docker build -t my-node-app .
# Run the container
$ docker run -p 8080:8080 -d my-node-app

This will create a Docker container that runs your Node.js application on port 8080.

4. Pushing to Docker Hub

If you want to share your container, you can push it to Docker Hub:

# Log in to Docker Hub
$ docker login
# Tag your image
$ docker tag my-node-app yourdockerhubusername/my-node-app
# Push to Docker Hub
$ docker push yourdockerhubusername/my-node-app

Once pushed, your containerized app can be pulled from Docker Hub to run anywhere with Docker installed.

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

top-home