Home >Web Front-end >JS Tutorial >How to Use Node.js with Docker
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:
Key Benefits
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.
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:
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!