Beginners’ Guide: Simple Node.js Application with Docker and Docker-Compose

Chaewonkong
2 min readApr 28, 2023
Create Node App with Docker & Docker Compose

Docker is a popular platform that simplifies the process of building, shipping, and running applications within containers. Docker Compose, on the other hand, is a tool for defining and running multi-container Docker applications. In this blog post, we’ll create a simple Node.js application, containerize it with Docker, and run it using Docker Compose.

Prerequisites:

  • Docker and Docker Compose installed on your system
    (If you are Mac or Windows User, download Docker Desktop)
  • Basic knowledge of Node.js and JavaScript

Node App With Docker And Docker Compose

Step 1

Creating the Node.js Application Create a new directory for your project and initialize it with npm:

$ mkdir node-docker-app
$ cd node-docker-app
$ npm init -y

Next, create a new file called app.js and add the following code:

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}`);
});

Install the express package:

$ npm install express

You can now run the application with:

$ node app.js

Step 2

Creating the Dockerfile Create a new file called Dockerfile in your project directory, and add the following:

# Use the official Node.js image as the base image
FROM node:16.14.0-alpine
# If you're using M1, M2 Mac, try this:
# FROM --platform=linux/amd64 node:16.14.0-alpine

# Set the working directory
WORKDIR /usr/src/app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the application files
COPY . .

# Expose the port
EXPOSE 3000

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

Step 3

Building the Docker Image Run the following command to build the Docker image:

$ docker build -t node-docker-app .

Step 4

Creating the Docker Compose File Create a new file called docker-compose.yml in your project directory, and add the following:

version: '3.8'
services:
app:
build: .
ports:
- '3000:3000'
environment:
- PORT=3000

Step 5

Running the Application with Docker Compose Run the application using Docker Compose:

$ docker-compose up

You should now be able to access the application at http://localhost:3000.

Conclusion

In this blog post, we created a simple Node.js application, containerized it with Docker, and ran it using Docker Compose. This process enables easier deployment, scaling, and management of applications across various environments.

--

--