Home >Web Front-end >JS Tutorial >How to Use Node.js with Docker

How to Use Node.js with Docker

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-08 11:49:09118browse

This tutorial demonstrates the advantages of using Docker containers for Node.js applications and establishes an efficient development workflow.

Node.js empowers the creation of fast and scalable web applications using JavaScript on both the server and client sides. While your application might function flawlessly on your development machine, its consistent performance across different environments (colleagues' machines, production servers) isn't guaranteed. Consider these potential issues:

  • Operating System Variations: Your development environment might be macOS, while colleagues use Windows, and the production server runs Linux.
  • Node.js Version Inconsistency: You might use Node.js 20, but others employ various versions.
  • Dependency Differences: Databases and other dependencies may vary or be unavailable on different platforms.
  • Security Concerns: Unforeseen security risks could arise when deploying code to diverse operating systems.

Key Benefits

  • Cross-Platform Compatibility: Docker solves the "it works on my machine" problem by enabling Node.js applications to run in isolated container environments.
  • Simplified Node.js App Deployment in Docker: We'll guide you through creating a basic Node.js script and executing it within a Docker container.
  • Enhanced Node.js Development Workflow: We'll show how Docker streamlines the development process for Node.js applications.

Docker's Solution

Docker effectively addresses the aforementioned compatibility challenges. Instead of installing applications directly, you run them inside lightweight, isolated virtual machine-like environments called containers.

How to Use Node.js with Docker

Unlike virtual machines that emulate entire PC hardware and operating systems, Docker emulates an OS, allowing you to install applications directly. It's common practice to run one application per Linux-based container and connect them via a virtual network for HTTP communication.

The advantages are numerous:

  • Consistent Environment: Your Docker setup mirrors your production Linux server, simplifying deployment.
  • Simplified Dependency Management: Download, install, and configure dependencies in minutes.
  • Cross-Platform Consistency: Your containerized app behaves identically across all platforms.
  • Enhanced Security: If your app malfunctions within a container, it won't affect your host machine; you can easily restart the container.

With Docker, installing Node.js locally or using runtime managers like nvm becomes unnecessary.

Your First Node.js Script

Install Docker Desktop (Windows, macOS, or Linux). Create a simple script named version.js:

<code class="language-javascript">console.log(`Node.js version: ${process.version}`);</code>

If Node.js is installed locally, run it to see the version. Now, run it within a Docker container (using the latest LTS Node.js version):

(macOS/Linux)

<code class="language-bash">$ docker run --rm --name version -v $PWD:/home/node/app -w /home/node/app node:lts-alpine version.js</code>

(Windows PowerShell)

<code class="language-powershell">> docker run --rm --name version -v ${PWD}:/home/node/app -w /home/node/app node:lts-alpine version.js</code>

The first run might take a few moments as Docker downloads dependencies. Subsequent runs are much faster. You can easily switch Node.js versions (e.g., node:21-alpine). The script executes within a Linux container with a specific Node.js version.

Command Breakdown:

  • docker run: Starts a container from an image.
  • --rm: Removes the container upon termination.
  • --name version: Assigns a name to the container.
  • -v $PWD:/home/node/app: Mounts the current directory as a volume inside the container.
  • -w /home/node/app: Sets the working directory within the container.
  • node:lts-alpine: Specifies the Docker image (LTS Node.js on Alpine Linux).
  • version.js: The command to execute.

Docker images are available on Docker Hub, offering various versions tagged with identifiers like :lts-alpine, 20-bullseye-slim, or latest. Alpine Linux is a lightweight distribution ideal for simple projects.

Running More Complex Applications

For applications with dependencies and build steps (using npm), a custom Docker image is necessary. This example uses Express.js:

Create a directory named simple, add package.json:

<code class="language-json">{
  "name": "simple",
  "version": "1.0.0",
  "description": "simple Node.js and Docker example",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "debug": "node --watch --inspect=0.0.0.0:9229 index.js",
    "start": "node index.js"
  },
  "license": "MIT",
  "dependencies": {
    "express": "^4.18.2"
  }
}</code>

And index.js:

<code class="language-javascript">// Express application
import express from 'express';

// configuration
const cfg = {
  port: process.env.PORT || 3000
};

// initialize Express
const app = express();

// home page route
app.get('/:name?', (req, res) => {
  res.send(`Hello ${req.params.name || 'World'}!`);
});

// start server
app.listen(cfg.port, () => {
  console.log(`server listening at http://localhost:${cfg.port}`);
});</code>

Create a Dockerfile:

<code class="language-dockerfile"># base Node.js LTS image
FROM node:lts-alpine

# define environment variables
ENV HOME=/home/node/app
ENV NODE_ENV=production
ENV NODE_PORT=3000

# create application folder and assign rights to the node user
RUN mkdir -p $HOME && chown -R node:node $HOME

# set the working directory
WORKDIR $HOME

# set the active user
USER node

# copy package.json from the host
COPY --chown=node:node package.json $HOME/

# install application modules
RUN npm install && npm cache clean --force

# copy remaining files
COPY --chown=node:node . .

# expose port on the host
EXPOSE $NODE_PORT

# application launch command
CMD [ "node", "./index.js" ]</code>

Build the image: docker image build -t simple .

Run the container: docker run -it --rm --name simple -p 3000:3000 simple

Access the app at http://localhost:3000/.

A .dockerignore file can prevent unnecessary files from being copied into the image.

Improved Development Workflow with Docker Compose

The previous method is inefficient for development. Docker Compose provides a better solution. Create docker-compose.yml:

<code class="language-yaml">version: '3'

services:

  simple:
    environment:
      - NODE_ENV=development
    build:
      context: ./
      dockerfile: Dockerfile
    container_name: simple
    volumes:
      - ./:/home/node/app
    ports:
      - "3000:3000"
      - "9229:9229"
    command: /bin/sh -c 'npm install && npm run debug'</code>

Start with docker compose up. Changes to index.js trigger automatic restarts. Use VS Code's debugger (attach to port 9229) for enhanced debugging. Stop with docker compose down.

Conclusion

While Docker requires initial setup, the long-term benefits of reliable, distributable code are significant. This tutorial covers the fundamentals; explore further resources for advanced usage. The images are retained for brevity.

The above is the detailed content of How to Use Node.js with Docker. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn