Tutorials  /  JavaScript

Dockerizing Node.js: Easily Create a Development Environment

Ccentron Redaktion · November 2024 ·4 min read ·JavaScript, Tutorial

Using Docker can significantly simplify development and deployment processes. Especially during active development, containerization offers numerous advantages.

In this tutorial, we’ll show you how to set up a development environment for a Node.js application using Docker and Docker Compose.

Using containers in development brings several benefits:

  • Consistent Environments: You can choose the languages and dependencies for your project without worrying about system conflicts.
  • Isolated Environments: This makes debugging easier and simplifies onboarding for new team members.
  • Portability: You can easily package and share your code.

Step 1: Clone the Project and Adjust Dependencies

The first step is to clone the project and adjust the dependencies in the `package.json` file. Add `nodemon` as a `devDependency` to enable automatic restarts during development.

git clone https://github.com/do-community/nodejs-mongo-mongoose.git node_project

cd node_project

nano package.json

"dependencies": {

"ejs": "^2.6.1",

"express": "^4.16.4",

"mongoose": "^5.4.10"

},

"devDependencies": {

"nodemon": "^1.18.10"

}

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Step 2: Configure the Application for Containers

Adjust your application to prepare it for working with containers. Refactor the code to use environment variables and dynamically set up the database connection.

nano app.js

const port = process.env.PORT || 8080;

app.listen(port, function () {

console.log(`Example app listening on ${port}!`);

});

Step 3: Adjust Database Connection Settings

Make your database connection more robust by adding code that handles cases where the application cannot connect to the database.

nano db.js

const {

MONGO_USERNAME,

MONGO_PASSWORD,

MONGO_HOSTNAME,

MONGO_PORT,

MONGO_DB

} = process.env;

const options = {

useNewUrlParser: true,

reconnectTries: Number.MAX_VALUE,

reconnectInterval: 500,

connectTimeoutMS: 10000,

};

const url = `mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOSTNAME}:${MONGO_PORT}/${MONGO_DB}?authSource=admin`;

mongoose.connect(url, options).then( function() {

console.log('MongoDB is connected');

})

.catch( function(err) {

console.log(err);

});

Step 4: Define Services with Docker Compose

Define the services with Docker Compose by creating the `docker-compose.yml` file with the definitions for your services.

nano docker-compose.yml

version: '3'

services:

nodejs:

build:

context: .

dockerfile: Dockerfile

image: nodejs

container_name: nodejs

restart: unless-stopped

env_file: .env

environment:

- MONGO_USERNAME=$MONGO_USERNAME

- MONGO_PASSWORD=$MONGO_PASSWORD

- MONGO_HOSTNAME=db

- MONGO_PORT=$MONGO_PORT

- MONGO_DB=$MONGO_DB

ports:

- "80:8080"

volumes:

- .:/home/node/app

- node_modules:/home/node/app/node_modules

networks:

- app-network

command: ./wait-for.sh db:27017 -- /home/node/app/node_modules/.bin/nodemon app.js

db:

image: mongo:4.1.8-xenial

container_name: db

restart: unless-stopped

env_file: .env

environment:

- MONGO_INITDB_ROOT_USERNAME=$MONGO_USERNAME

- MONGO_INITDB_ROOT_PASSWORD=$MONGO_PASSWORD

volumes:

- dbdata:/data/db

networks:

- app-network

networks:

app-network:

driver: bridge

volumes:

dbdata:

node_modules:

Step 5: Test the Application

Test your application by creating the containers with the `docker-compose up` command and checking if data persistence works.

Conclusion

By containerizing your Node.js application with Docker, you've created a flexible and portable development environment. You can now develop and deploy your code independently of the underlying infrastructure.

This tutorial provides a solid foundation for getting started with application development in containerized environments. It is recommended to explore further resources to deepen your knowledge of Docker and containerization. Dockerizing Node.js: Easily Create a Development Environment

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren