在Docker环境下,你可以使用以下的bash脚本来实现你的需求。这个脚本首先运行一个PostgreSQL数据库容器,然后启动一个FastAPI容器并将其连接到先前创建的网络。
#!/bin/bash
# PostgreSQL container configuration
PG_CONTAINER_NAME="my_pg_container"
PG_PORT=5432
PG_VOLUME_ALIAS="pg_data_volume"
PG_USER="my_user"
# Create the network (if not already created)
docker network create my_network || true
# Run the PostgreSQL container
docker run -d \
--name $PG_CONTAINER_NAME \
--network=my_network \
-p $PG_PORT:5432 \
-v pg_data:/var/lib/postgresql/data # replace 'pg_data' with your actual data volume path, or use named volume like `-v $PG_VOLUME_ALIAS:/var/lib/postgresql/data`
-e POSTGRES_USER=$PG_USER \
postgres
# FastAPI container configuration
FASTAPI_CONTAINER_NAME="my_fastapi_container"
# Run the FastAPI container, assuming you have built a Docker image named "my_fastapi_image"
docker run -d \
--name $FASTAPI_CONTAINER_NAME \
--network=my_network \
-e DATABASE_HOST=$PG_CONTAINER_NAME \
-e DATABASE_PORT=$PG_PORT \
-e DATABASE_USER=$PG_USER \
my_fastapi_image
# Replace the environment variables above with the actual connection details for your FastAPI application to connect to the PostgreSQL database.
# Note: You might also need additional env vars depending on your setup, such as DATABASE_NAME and potentially DATABASE_PASSWORD if you've set one.
# Make sure to adjust the Docker image name, port mappings, volume paths, and environment variables according to your specific requirements.
请根据你的实际需求调整上述脚本中的变量和设置,例如:Docker镜像名称、端口映射、数据卷路径以及环境变量等。同时,FastAPI应用需要正确配置以使用这些环境变量来连接到PostgreSQL数据库。