Docker+Deno:容器化 Deno Hello World 服务器 短版 长版

2025-06-08

Docker+Deno:容器化 Deno hello world 服务器

简短版本

长版本

Deno 是当下的流行词,我们仍然不知道它将如何结束。

老实说,我非常喜欢 node,但我很感兴趣,所以我用 deno 创建了一个 hello world 服务器,并立即尝试用 docker 将其容器化。

警告!
此示例基于此 docker 镜像https://hub.docker.com/r/hayd/deno

这不是官方的 deno 存储库

Github 仓库:https://github.com/FrancescoXX/deno-docker

请注意这是我第一次使用 deno,所以这对我来说也是一个相当新的东西

简短版本

你可以直接克隆存储库

git clone https://github.com/FrancescoXX/deno-docker
Enter fullscreen mode Exit fullscreen mode

导航到 docker-compose.yml 所在的文件夹,然后运行

docker-compose up --build
Enter fullscreen mode Exit fullscreen mode

完毕!


长版本

如果您想继续,并且使用 Visual Studio Code,我建议您安装此扩展:

替代文本

首先,我们为 deno 依赖项创建一个名为 deps.ts 的文件。

在 Deno 中,我们直接从 URL 导入第三方代码,不需要 node_modules 或 package.json

export { serve } from "https://deno.land/std@0.50.0/http/server.ts";
Enter fullscreen mode Exit fullscreen mode

然后,我们创建 main.ts 文件,并将 deps.ts 文件作为常规 ts 文件导入

我们还根据官方示例定义了一个非常简单的服务器

import { serve } from "./deps.ts";

const PORT = 8000;

const s = serve({ port: 8000 });

const body = new TextEncoder().encode("Hello World\n");

console.log(`Server started on port ${PORT}`);
for await (const req of s) {
  req.respond({ body });
}
Enter fullscreen mode Exit fullscreen mode

然后,我们使用 hayd/alpine-deno:1.0.0 镜像创建一个非常简单的 Dockerfile

FROM hayd/alpine-deno:1.0.0

EXPOSE 8000

WORKDIR /app

USER deno

COPY deps.ts .
RUN deno cache deps.ts

COPY . .
RUN deno cache main.ts

CMD ["run", "--allow-net", "main.ts"]
Enter fullscreen mode Exit fullscreen mode

最后,我们创建一个非常简单的 docker-compose.yml 文件,目前不需要,但将来可能会有用,例如,如果我们开始使用数据库或其他服务

我们将端口 8000 定义为内部和外部端口以及默认网络

version: "3.7"

services:
  deno:
    image: "deno-docker:0.0.1"
    build: .
    ports:
      - "8000:8000"
    networks: 
      - deno

networks:
  deno: {}
Enter fullscreen mode Exit fullscreen mode

从 docker-compose.yml 文件所在的文件夹中,我们构建镜像:

docker-compose build
Enter fullscreen mode Exit fullscreen mode

最后,我们可以用这个命令启动服务

docker-compose up deno
Enter fullscreen mode Exit fullscreen mode

从浏览器访问 localhost:8000

替代文本

这不是最好和最有用的服务器,但它旨在作为一个起点

此外,使用 docker,我们不需要在机器上安装 deno

如果您需要更多关于此主题的文章,请发表评论

Github 仓库:Github 仓库:https://github.com/FrancescoXX/deno-docker

鏂囩珷鏉ユ簮锛�https://dev.to/francescoxx/docker-deno-containerize-a-deno-hello-world-server-1ha1
PREV
Go + TypeScript 全栈 Web 应用程序,带有 nextjs、PostgreSQL 和 Docker
NEXT
Rust 开发人员的新项目?AWS Security LIVE!