Dockerize 简单 Application
你将构建什么
Docker 镜像 for 简单节点.js web application 那个能 是构建 and 运行 anywhere 使用单个 command.
学习目标
- 理解结构的 Dockerfile
- 学习到 构建 Docker 镜像从 Dockerfile
- 运行容器从 镜像 and access application
- 理解镜像 layering and 缓存
前置要求
- 基础 command 行 skills
- Docker 安装 on 你的 machine
- 简单节点.js application (我们 provide starter)
步骤
- 1
创建简单节点.js app
创建基础 Express.js 服务器那个 responds 使用 'Hello 从 Docker!' on port 3000. 创建包.JSON and app.js files.
代码// app.js const express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello from Docker!')); app.listen(3000, () => console.log('Server running on port 3000'));预期结果
你有 工作节点.js app 那个运行 locally 使用
节点 app.js. - 2
编写 Dockerfile
创建 file named
Dockerfile(否 extension) 那个开始从 official 节点.js 镜像, 设置工作 directory, 复制包 files, 安装 dependencies, 复制 app code, and 定义开始 command.代码FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "app.js"]预期结果
Dockerfile exists in 你的项目根 那个描述如何 构建镜像.
- 3
构建 Docker 镜像
Use
docker 构建command 到创建镜像从 你的 Dockerfile. 标签它 使用 name 所以你 能引用它 later.代码docker build -t my-node-app .预期结果
Docker 构建镜像 layer 通过 layer and shows 成功消息. 运行
docker 镜像到 see 它. - 4
运行容器
Use
docker 运行到开始容器从 你的镜像. 映射 port 3000 从容器到 port 3000 on 你的 host 所以你 能 access 它 in 浏览器.代码docker run -p 3000:3000 my-node-app预期结果
打开 http://localhost:3000 in 你的浏览器 and see 'Hello 从 Docker!'
- 5
添加健康检查端点
为应用添加 /health 端点返回 200 OK,供编排系统(Kubernetes、负载均衡器)探测存活。健康检查是生产部署的基础设施。
代码# app.py (Flask example) from flask import Flask, jsonify app = Flask(__name__) @app.route("/health") def health(): return jsonify({"status": "ok"}), 200 @app.route("/ready") def ready(): # Check DB connection etc. return jsonify({"ready": True}), 200预期结果
curl localhost:5000/health 返回 {"status":"ok"} 和 200 状态码。
自己动手试试
你学到了什么
你学习如何 containerize application 使用 Docker: 编写 Dockerfile, 构建镜像, and 运行容器. 这个是 基础的 所有容器-based DevOps workflows.
相关资源
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。