Deploying an Express.js application using Docker can streamline your development process and ensure consistency across different environments. This step-by-step guide will walk you through the essential steps to containerize and deploy your Express.js app with Docker.

Prerequisites

  • Node.js and npm installed on your machine
  • Docker installed and running
  • Basic knowledge of Express.js and Docker commands

Step 1: Create Your Express.js Application

Start by initializing a new Node.js project and creating a simple Express.js server.

Open your terminal and run:

mkdir my-express-app && cd my-express-app

npm init -y

npm install express

Create a file named app.js with the following content:

const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => res.send('Hello, Docker!'));

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 2: Create a Dockerfile

In the root directory of your project, create a file named Dockerfile with the following content:

FROM node:14

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["node", "app.js"]

Step 3: Build the Docker Image

In your terminal, run the following command to build your Docker image:

docker build -t my-express-app .

Step 4: Run the Container

Once the image is built, run a container with the following command:

docker run -d -p 4000:3000 --name express-container my-express-app

This maps port 3000 inside the container to port 4000 on your host machine.

Step 5: Verify Deployment

Open your browser and navigate to http://localhost:4000. You should see the message Hello, Docker!.

Additional Tips

  • Use docker-compose for managing multi-container applications.
  • Optimize your Dockerfile by using multi-stage builds for production.
  • Regularly update your base images to include security patches.

Deploying your Express.js app with Docker simplifies development and deployment workflows, making it easier to scale and manage your applications.