在 Docker 中安装 Node.js 非常简单,以下是具体步骤:
1. 使用官方 Node.js 镜像
Docker Hub 提供了官方的 Node.js 镜像,可以直接使用它来运行 Node.js 应用。
1.1 拉取 Node.js 镜像
首先,从 Docker Hub 拉取官方的 Node.js 镜像:
sudo docker pull node
这将会拉取最新的 Node.js 镜像。如果需要特定版本,可以指定版本号,例如:
sudo docker pull node:16
2. 创建并运行 Node.js 容器
2.1 创建一个简单的 Node.js 应用
假设你有一个简单的 Node.js 应用,文件结构如下:
/app └── server.js
server.js
内容如下:
const http = require('http'); const hostname = '0.0.0.0'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
2.2 创建 Dockerfile
在 /app
目录下,创建一个 Dockerfile
文件,内容如下:
# 使用官方 Node.js 镜像作为基础镜像 FROM node:16 # 设置工作目录 WORKDIR /usr/src/app # 将当前目录的文件复制到容器中 COPY . . # 安装依赖(如果有 package.json 文件) RUN npm install # 暴露应用运行的端口 EXPOSE 3000 # 启动 Node.js 应用 CMD ["node", "server.js"]
2.3 构建镜像
进入 /app