.NET Core 3.1、Docker、PostgreSQL、Swagger、C#






4.11/5 (2投票s)
.NET Core 3.1、Docker、postgres、swagger 快速入门
必需
推荐
- 本地安装 dotnet core 3.1
- DBBeaver
概述和介绍
你是否对 .NET Core 感兴趣,但不知道从哪里开始? 事实上,要找到关于“你的第一个 .NET Core API”的全面资料,甚至将其连接到 Postgres 都是很困难的。 本快速入门旨在为你提供一个模板,只需两个命令即可运行,并为你提供继续构建本地应用程序的机会。
快速入门提供了一个包含以下内容的 API:
GET
请求POST
请求- PostgreSQL 连接
- Swagger 集成
这个演示应用程序将完全在 docker 中运行。 简单地构建容器
docker-compose build
构建将编译应用程序并移出入口点 shell 脚本,准备执行。 这一步很重要,我们希望数据库迁移在容器启动后但在应用程序尝试连接之前运行。 迁移将在数据库中创建表。
Docker 文件
FROM mcr.microsoft.com/dotnet/core/sdk:3.1
COPY . /app
WORKDIR /app
RUN dotnet tool install --global dotnet-ef
RUN dotnet restore
RUN dotnet build
RUN chmod +x ./entrypoint.sh
CMD /bin/bash ./entrypoint.sh
entrypoint.sh
#!/bin/bash
set -e
run_cmd="dotnet run --no-build --urls http://0.0.0.0:5000 -v d"
export PATH="$PATH:/root/.dotnet/tools"
until dotnet ef database update; do
>&2 echo "Migrations executing"
sleep 1
done
>&2 echo "DB Migrations complete, starting app."
>&2 echo "Running': $run_cmd"
exec $run_cmd
然后启动
docker-compose up
这将启动两个容器。 PostgreSQL 是完全标准的,我们只是传入一个环境变量,即数据库(postgres)的密码。 这里的小技巧是,init.sql 脚本也挂载在主机(本地机器)和容器之间。 该脚本被复制到数据库容器启动时执行的位置。 它非常简单。 它将删除名为“Posts
”的数据库(如果存在),然后重新创建它,以便我们从头开始。 此配置位于“docker-compose.yml”文件中。
docker-compose.yml:
version: '3'
services:
web:
container_name: dotnetCore31
build: .
ports:
- "5005:5000"
depends_on:
- database
database:
container_name: database
image: postgres:latest
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=password
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
应用程序启动后,你可以通过 https://:5005/swagger 访问来测试 API。
你也可以通过连接到 localhost 端口 5432 使用你最喜欢的工具连接到数据库。 我推荐并使用 DBBeaver:设置如下
host: localhost
port: 5432
database: postgres
user: postgres
password: postgres
如果你想在本地运行应用程序,请添加一个本地主机条目。 容器内部 DNS 知道要将 database 解析为 postgres(在 docker-compse.yml 文件第 10 行中定义的名称)容器,因此将此别名添加到你的 hosts 文件将允许你的 VSCode 或 Visual Studio 项目执行并连接到数据库。
或者,将 appsettings.Development.json 中的连接字符串更改为 localhost(从 database)。
#windows: c:\windows\system32\drivers\etc\hosts
Linux/MacOS: /etc/hosts
127.0.0.1 database
我更喜欢使用 Visual Studio。 要在本地运行应用程序,只需双击 pgapp.sln 文件,然后单击 运行。 你的应用程序将编译并在本地运行,并且可以通过端口 5000 访问。
本地 URL:https://:5000/swagger