tlmfoundationcosmetics.com

Dockerizing Your First Express.js App: A Comprehensive Guide

Written on

Chapter 1: Setting Up Your Express.js Application

In this chapter, we will build a basic Express.js application. Once the application is developed, we will create a Docker image to run it locally. This approach is beneficial for anyone looking to develop microservices or applications that operate within a Docker environment.

Initialize Your Repository

npm init -y

Install Dependencies

Express version 5 now supports asynchronous route handlers. While this version is still in beta, we can expect a stable release soon.

npm i [email protected]

For your reference, below is the suggested folder structure for the project.

Creating an Express Application

Within the src directory, create an index.js file with the following content:

const express = require("express");

const app = express();

const port = 3000;

app.get("/", async (req, res) => {

res.send("Hello Medium!");

});

app.listen(port, () => {

console.log(Your app is running on http://localhost:${port});

});

We can also enhance the package.json file to streamline our development process. To avoid the need to restart the application manually each time, we can enable watch mode. For this, we need to use nodemon in earlier versions:

{

"name": "medium-app",

"version": "1.0.0",

"description": "",

"main": "./src/index.js",

"scripts": {

"start": "node ./src/index.js",

"start:dev": "node --watch ./src/index.js"

},

"keywords": [],

"author": "",

"license": "ISC",

"dependencies": {

"express": "^5.0.0-beta.3"

}

}

At this point, your application should function correctly.

Running the Application

With Docker, we can assign a unique port for each container. This needs to be reflected in our code:

const express = require("express");

if (!process.env.PORT) {

throw new Error("Please specify a port");

}

const app = express();

const port = process.env.PORT;

app.get("/", async (req, res) => {

res.send("Hello Medium!");

});

app.listen(port, () => {

console.log(Your app is running on http://localhost:${port});

});

Creating the Dockerfile

Next, we will create a Dockerfile in the root directory. In production scenarios, you can use npm ci --omit=dev to install dependencies while excluding development packages:

FROM node:21.7-alpine

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm ci --omit=dev

COPY ./src ./src

CMD npm start

Don’t forget to establish a .dockerignore file. If your Docker builds are taking longer than expected, it could be because they are processing too many files. The .dockerignore file allows you to specify which files and directories should be excluded from the build process:

.idea

.git

node_modules

Building the Docker Image

To create your Docker image, run the following command:

docker build -t medium-docker --file Dockerfile .

Running the Docker Container

Start your application with:

docker run -d -p 3000:3000 -e PORT=3000 medium-docker

Cleaning Up

To manage your containers, first, list them to find the ID of the running container:

docker container list

Next, you can stop and remove the container with the following commands:

docker stop <container_id>

docker rm <container_id>

Your application should now be running smoothly within Docker.

Thank you for reading this guide! I hope you found it informative. If you have any feedback or questions, please feel free to reach out.

In Plain English 🚀

Thank you for being a part of the In Plain English community! Don’t forget to clap and follow the writer ️👏️️. Follow us on: X | LinkedIn | YouTube | Discord | Newsletter. Explore more content on Stackademic | CoFeed | Venture | Cubed at PlainEnglish.io.

Chapter 2: Learning Through Video Tutorials

For those who prefer visual learning, here are two valuable video resources that guide you through Dockerizing a Node.js application:

The first video, "Dockerizing a Node.js Express Application: Complete Guide for Beginners," provides a thorough introduction to the process:

The second video, "How to Build Node.js Apps with Docker," offers additional insights and practical examples:

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Conquering My Fear of Water: A Journey to the Triathlon

A personal journey of overcoming fear of swimming and achieving the impossible through a triathlon.

Finding Balance: Nurturing Your Inner Self for Growth

Explore the internal struggle between positivity and negativity, and how self-awareness can help you nurture your inner angel.

Navigating Uncertainty: Strategies for Clarity and Confidence

Explore effective strategies to mitigate uncertainty in personal and professional life through enhanced communication and transparency.

Title: Evaluating the 20% Down Payment: Pros and Cons for Homebuyers

This article examines the advantages and disadvantages of making a 20% down payment when purchasing a home.

Renewable Energy Investment Trends from Global CEOs Explored

Analyzing trends in renewable energy investments from leading CEOs and producers, highlighting key strategies and geopolitical impacts.

Latest Insights into Energy and Commodities Markets in 2024

Explore the latest developments in energy and commodities at CERAWeek 2024, featuring key insights from industry leaders.

The Transformative Power of Walking: A Path to Wellness

Discover how walking can enhance your well-being and support metabolic health.

The Interplay of Quantum Physics and Jungian Psychology

Explore the connections between quantum physics and Jungian psychology, revealing the profound implications for understanding reality and consciousness.