Week 1 - 网络 & 云

Lab 2 Encapsulate (封装) Rust Application into Docker image

将写好的Rust程序打包成 Docker 镜像

Rust | Docker Docs

Click above to learn about build rust application with docker. The official example seems not really clear about the Dockerfile. Here write a simple example that quickly introduce how to create rust app but reduce the final image size in a most simple way.

Simple Guide Making a Rust App Image

Step 1 Write the Dockerfile

在你的软件包根目录下添加 Dockerfile :

# Image pre-built from the official Rust image
# base on the Debian Bullseye slim image
FROM rust:1.83.0-slim-bullseye AS base

# Copy the source code and the Cargo.toml file
COPY ./Cargo.toml ./Cargo.toml
COPY ./src ./src
RUN cargo build --release

# Image to run the final binary
FROM debian:bullseye-slim

# It's usual to set the working directory to /app
WORKDIR /app

# Only copy the final binary from the build stage
# The binary is located at /app/target/release/example-actix-helloworld, 
#   since we are using the release profile.
COPY --from=base /target/release/example-actix-helloworld /app/example-actix-helloworld

# Finally, we run the binary
CMD ["./example-actix-helloworld"]

此例子仅用于展示 Dockerfile 一部分工作原理,更多关于 Dockerfile 请查看文档 Dockerfile Reference 。注意,在这里,你应该将 example-actix-helloworld 替换为你的软件包名(在Cargo.toml中显示)。

在这里,我们首先使用了一个包含了 Rust 编译环境的基于Debian的镜像来编译我们的二进制程序,以保证其与后面不包含编译环境的、较小的Debian镜像可以二进制兼容。拷贝必要的源码,执行构建,然后直接将二进制程序拷贝进后者中运行,这就是这个 Dockerfile 做的事情。

Step 2 Build the Docker Image

软件包根目录下执行下面代码

docker buildx build -t actix-example:v0.1 .

-t 可任意自定义名称

-t, --tag stringArray
Name and optionally a tag (format: “name:tag”)

Step 3 Run the Image

docker run -p 8888:8888 actix-example:v0.1

-p [本机端口号]:[容器内端口号]

现在会在前台卡住,实际上就是已经在运行啦!尝试 curl 一下吧

Go Further

编译优化

不知道有没有发现,当修改了源码后,重新构建镜像,他会把所有crate重新下载一边编译!这很慢!为了优化这个,可进一步参考:
Best practice Dockerfile for speedy Rust builds

更多运行参数

尝试 docker run 增加 -d 参数,他直接返回到了命令行,为什么?docker ps 看看?

完整命令

docker run -d -p 8888:8888 actix-example:v0.1

容器网络互访

容器实例默认启动在 bridge 网络上,分配有一般是 172.17.x.x 的网络。尝试不通过端口映射,直接在 bridge 网络中让 Swagger Editor 访问你的 Web App!

2 个赞