開發您的 Rust 應用程式
先決條件
- 您已安裝最新版本的 Docker Desktop.
- 您已完成 Docker Desktop 學習中心 中的演練,瞭解 Docker 概念。
- 您擁有一個 git 客戶端。
概述
在本節中,您將學習如何在 Docker 中使用卷和網路。您還將使用 Docker 構建映象,並使用 Docker Compose 使一切都變得更加輕鬆。
首先,您將瞭解如何在容器中執行資料庫,以及如何使用卷和網路來持久化您的資料並讓您的應用程式與資料庫通訊。然後,您將把所有內容整合到一個 Compose 檔案中,該檔案允許您使用一個命令設定和執行本地開發環境。
在容器中執行資料庫
與其下載 PostgreSQL、安裝、配置,然後將其作為服務執行,您可以使用 Docker 的官方 PostgreSQL 映象並在容器中執行它。
在您在容器中執行 PostgreSQL 之前,請建立一個 Docker 可以管理的卷,用於儲存您的持久資料和配置。使用 Docker 提供的命名卷功能,而不是使用繫結掛載。
執行以下命令建立您的卷。
$ docker volume create db-data
現在,建立一個網路,您的應用程式和資料庫將使用該網路相互通訊。該網路稱為使用者定義的橋接網路,它為您提供了一個不錯的 DNS 查詢服務,您可以在建立連線字串時使用它。
$ docker network create postgresnet
現在,您可以在容器中執行 PostgreSQL,並將其附加到您之前建立的卷和網路。Docker 會從 Hub 中拉取映象,並在本地執行它。在以下命令中,選項 --mount
用於啟動帶有卷的容器。有關更多資訊,請參閱 Docker 卷。
$ docker run --rm -d --mount \
"type=volume,src=db-data,target=/var/lib/postgresql/data" \
-p 5432:5432 \
--network postgresnet \
--name db \
-e POSTGRES_PASSWORD=mysecretpassword \
-e POSTGRES_DB=example \
postgres
現在,請確保您的 PostgreSQL 資料庫正在執行,並且您可以連線到它。連線到容器內的執行中的 PostgreSQL 資料庫。
$ docker exec -it db psql -U postgres
您應該看到類似於以下內容的輸出。
psql (15.3 (Debian 15.3-1.pgdg110+1))
Type "help" for help.
postgres=#
在之前的命令中,您透過將 psql
命令傳遞給 db
容器來登入到 PostgreSQL 資料庫。按 ctrl-d 退出 PostgreSQL 互動式終端。
獲取並執行示例應用程式
對於示例應用程式,您將使用 Awesome Compose 中的 react-rust-postgres 應用程式的後端變體。
使用以下命令克隆示例應用程式倉庫。
$ git clone https://github.com/docker/docker-rust-postgres
在克隆的倉庫目錄中,執行
docker init
建立必要的 Docker 檔案。請參考以下示例來回答docker init
中的提示。$ docker init Welcome to the Docker Init CLI! This utility will walk you through creating the following files with sensible defaults for your project: - .dockerignore - Dockerfile - compose.yaml - README.Docker.md Let's get started! ? What application platform does your project use? Rust ? What version of Rust do you want to use? 1.70.0 ? What port does your server listen on? 8000
在克隆的倉庫目錄中,在 IDE 或文字編輯器中開啟
Dockerfile
以更新它。docker init
負責建立Dockerfile
中的大多數指令,但您需要為您的獨特應用程式更新它。除了src
目錄之外,此應用程式還包含一個migrations
目錄來初始化資料庫。將migrations
目錄的繫結掛載新增到Dockerfile
中構建階段。以下是更新後的Dockerfile
。# syntax=docker/dockerfile:1 # Comments are provided throughout this file to help you get started. # If you need more help, visit the Dockerfile reference guide at # https://docs.docker.net.tw/reference/dockerfile/ ################################################################################ # Create a stage for building the application. ARG RUST_VERSION=1.70.0 ARG APP_NAME=react-rust-postgres FROM rust:${RUST_VERSION}-slim-bullseye AS build ARG APP_NAME WORKDIR /app # Build the application. # Leverage a cache mount to /usr/local/cargo/registry/ # for downloaded dependencies and a cache mount to /app/target/ for # compiled dependencies which will speed up subsequent builds. # Leverage a bind mount to the src directory to avoid having to copy the # source code into the container. Once built, copy the executable to an # output directory before the cache mounted /app/target is unmounted. RUN --mount=type=bind,source=src,target=src \ --mount=type=bind,source=Cargo.toml,target=Cargo.toml \ --mount=type=bind,source=Cargo.lock,target=Cargo.lock \ --mount=type=cache,target=/app/target/ \ --mount=type=cache,target=/usr/local/cargo/registry/ \ --mount=type=bind,source=migrations,target=migrations \ <<EOF set -e cargo build --locked --release cp ./target/release/$APP_NAME /bin/server EOF ################################################################################ # Create a new stage for running the application that contains the minimal # runtime dependencies for the application. This often uses a different base # image from the build stage where the necessary files are copied from the build # stage. # # The example below uses the debian bullseye image as the foundation for running the app. # By specifying the "bullseye-slim" tag, it will also use whatever happens to be the # most recent version of that tag when you build your Dockerfile. If # reproducability is important, consider using a digest # (e.g., debian@sha256:ac707220fbd7b67fc19b112cee8170b41a9e97f703f588b2cdbbcdcecdd8af57). FROM debian:bullseye-slim AS final # Create a non-privileged user that the app will run under. # See https://docs.docker.net.tw/develop/develop-images/dockerfile_best-practices/ #user ARG UID=10001 RUN adduser \ --disabled-password \ --gecos "" \ --home "/nonexistent" \ --shell "/sbin/nologin" \ --no-create-home \ --uid "${UID}" \ appuser USER appuser # Copy the executable from the "build" stage. COPY --from=build /bin/server /bin/ # Expose the port that the application listens on. EXPOSE 8000 # What the container should run when it is started. CMD ["/bin/server"]
在克隆的倉庫目錄中,執行
docker build
構建映象。$ docker build -t rust-backend-image .
執行
docker run
,並使用以下選項將映象作為容器執行在與資料庫相同的網路上。$ docker run \ --rm -d \ --network postgresnet \ --name docker-develop-rust-container \ -p 3001:8000 \ -e PG_DBNAME=example \ -e PG_HOST=db \ -e PG_USER=postgres \ -e PG_PASSWORD=mysecretpassword \ -e ADDRESS=0.0.0.0:8000 \ -e RUST_LOG=debug \ rust-backend-image
使用 curl 命令呼叫應用程式,以驗證它是否連線到資料庫。
$ curl https://:3001/users
您應該收到類似於以下內容的響應。
[{"id":1,"login":"root"}]
使用 Compose 在本地開發
當您執行 docker init
時,除了 Dockerfile
之外,它還會建立一個 compose.yaml
檔案。
此 Compose 檔案非常方便,因為您不必輸入所有需要傳遞給 docker run
命令的引數。您可以使用 Compose 檔案以宣告的方式完成此操作。
在克隆的倉庫目錄中,在 IDE 或文字編輯器中開啟 compose.yaml
檔案。docker init
負責建立大多數指令,但您需要為您的獨特應用程式更新它。
您需要更新 compose.yaml
檔案中的以下內容:
- 取消註釋所有資料庫指令。
- 在伺服器服務下新增環境變數。
以下是更新後的 compose.yaml
檔案。
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker compose reference guide at
# https://docs.docker.net.tw/compose/compose-file/
# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
server:
build:
context: .
target: final
ports:
- 8000:8000
environment:
- PG_DBNAME=example
- PG_HOST=db
- PG_USER=postgres
- PG_PASSWORD=mysecretpassword
- ADDRESS=0.0.0.0:8000
- RUST_LOG=debug
# The commented out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker compose up`.
depends_on:
db:
condition: service_healthy
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
請注意,該檔案沒有為這兩個服務指定網路。當您使用 Compose 時,它會自動建立一個網路,並將服務連線到它。有關更多資訊,請參閱 Compose 中的網路。
在您使用 Compose 執行應用程式之前,請注意,此 Compose 檔案指定了一個 password.txt
檔案來儲存資料庫的密碼。您必須建立此檔案,因為它不包含在源倉庫中。
在克隆的倉庫目錄中,建立一個名為 db
的新目錄,並在該目錄中建立一個名為 password.txt
的檔案,其中包含資料庫的密碼。使用您喜歡的 IDE 或文字編輯器,將以下內容新增到 password.txt
檔案中。
mysecretpassword
如果您有從上一節執行的任何其他容器,請停止 它們。
現在,執行以下 docker compose up
命令啟動您的應用程式。
$ docker compose up --build
該命令傳遞了 --build
標誌,因此 Docker 將編譯您的映象,然後啟動容器。
現在測試您的 API 端點。開啟一個新的終端,然後使用 curl 命令向伺服器發出請求。
$ curl https://:8000/users
您應該收到以下響應。
[{"id":1,"login":"root"}]
總結
在本節中,您瞭解瞭如何設定您的 Compose 檔案,以便使用單個命令執行您的 Rust 應用程式和資料庫。
相關資訊
下一步
在下一節中,您將瞭解如何使用 GitHub Actions 設定 CI/CD 管道。