Table of Contents
Containerizing your applications has become an essential skill for modern developers. In this tutorial, we will walk through the process of containerizing an Express.js application using Docker Compose. This approach simplifies deployment and ensures consistency across different environments.
Prerequisites
- Basic knowledge of Node.js and Express.js
- Docker installed on your machine
- Docker Compose installed
- A code editor like VS Code
Step 1: Set Up Your Express.js Application
Create a new directory for your project and initialize a basic Express.js server. Run the following commands:
mkdir express-docker
cd express-docker
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 from Dockerized Express.js!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 2: Create a Dockerfile
In the root directory, create a file named Dockerfile and add the following content:
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
Step 3: Create docker-compose.yml
Create a docker-compose.yml file in the root directory with the following content:
version: '3'
services:
app:
build: .
ports:
- "3000:3000"
Step 4: Build and Run the Container
Open your terminal in the project directory and run the following command to build and start your container:
docker-compose up --build
Once the build completes, open your browser and navigate to http://localhost:3000. You should see the message:
Hello from Dockerized Express.js!
Conclusion
You have successfully containerized an Express.js application using Docker Compose. This setup makes it easy to deploy and scale your application across different environments. Experiment with adding more services or configuring environment variables to further enhance your Docker setup.