跳到主要内容

部署

2024年07月07日
柏拉文
越努力,越幸运

一、认识


二、目录


|- index.js 
|- Dockerfile
|- .dockerignore
|- docker-compose.yml

三、index.js


const Koa = require("koa");
const KoaRouter = require("koa-router");

const app = new Koa();
const router = new KoaRouter();

router.get("/", async (ctx) => {
ctx.body = "Hello World!";
});

app.use(router.routes());

app.listen(3000, () => {
console.log("Server is running on port 3000");
});

四、Dockerfile


FROM node:latest
WORKDIR /service
COPY package*.json /service
RUN npm install
COPY . /service
EXPOSE 3000
CMD ["node", "index.js"]

五、.dockerignore


node_modules

六、docker-compose.yml


services:
node-hello-world:
image: node-hello-world
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
networks:
- node-hello-world-network

networks:
node-hello-world-network:
driver: bridge

七、构建和运行服务


在项目根目录下打开终端并运行以下命令:

docker-compose up --build

这个命令会执行以下操作:

  • 根据 Dockerfile 构建 node-hello-world 镜像。

  • 创建并启动一个容器,运行 Node.js 应用。

  • 映射容器内的端口 3000 到主机的端口 3000`。

八、验证服务


在浏览器中访问 http://localhost:3000,你应该会看到 "Hello World"