運行docker-compose up -d時,我希望創建 2 個資料庫。
碼頭工人-compose.yml:
version: '3.4'
volumes:
db_data:
services:
postgres:
image: postgres:alpine
environment:
- POSTGRES_PASSWORD=Password123
- POSTGRES_DB=database1
ports:
- "5432:5432"
platform:
image: image1/platform:${TAG:-latest}
build:
context: .
dockerfile: PlatformApi/Dockerfile
restart: on-failure
environment:
- ASPNETCORE_ENVIRONMENT=Local
- ConnectionStrings__DefaultConnection=Server=postgres;Port=5432;Uid=postgres;Pwd=Password123;Database=database1
ports:
- "5001:80"
depends_on:
- postgres
volumes:
- .docker/setup.sql:/docker-entrypoint-initdb.d/setup.sql
- db_data:/var/lib/mysql
identity:
image: image2/identity:${TAG:-latest}
build:
context: .
dockerfile: Identity/Dockerfile
restart: on-failure
environment:
- ASPNETCORE_ENVIRONMENT=Local
- ConnectionStrings__DefaultConnection=Server=postgres;Port=5432;Uid=postgres;Pwd=Password123;Database=database2
ports:
- "5002:80"
depends_on:
- postgres
volumes:
- .docker/setup.sql:/docker-entrypoint-initdb.d/setup.sql
- db_data:/var/lib/mysql
這是我的setup.sql檔案,位于.docker檔案夾內
CREATE DATABASE IF NOT EXISTS database1;
CREATE USER postgres IDENTIFIED BY Password123;
GRANT CREATE, ALTER, INDEX, LOCK TABLES, REFERENCES, UPDATE, DELETE, DROP, SELECT, INSERT ON database1.* TO postgres;
CREATE DATABASE IF NOT EXISTS database2;
CREATE USER postgres IDENTIFIED BY Password123;
GRANT CREATE, ALTER, INDEX, LOCK TABLES, REFERENCES, UPDATE, DELETE, DROP, SELECT, INSERT ON database2.* TO postgres;
FLUSH PRIVILEGES;
當我運行docker-compose up -d時,創建了 3 個容器,但其中 1 個容器因錯誤而退出database "database2" does not exist。
我做錯什么了?setup.sql檔案沒有執行還是內容不正確?
uj5u.com熱心網友回復:
在 postgres 服務中,您使用以下配置啟動資料庫
postgres:
image: postgres:alpine
environment:
- POSTGRES_PASSWORD=Password123
- POSTGRES_DB=database1
ports:
- "5432:5432"
結果database1創建了一個帶有名稱的資料庫
在以下服務中,您嘗試首先連接到資料庫
在平臺服務中:
- ConnectionStrings__DefaultConnection=...;Database=database1
這里沒有問題,因為database1存在
但在identity服務中:
- ConnectionStrings__DefaultConnection=...;Database=database2
您嘗試連接到database2哪個does not exist
它不存在的原因是race conditions您的setup.sql. 您不能保證當identity服務啟動時,服務database2已經創建了platform。
為了解決這個問題,您可以添加postgres2創建database2
postgres2:
image: postgres:alpine
environment:
- POSTGRES_PASSWORD=Password123
- POSTGRES_DB=database2
ports:
- "5433:5432"
identity:
image: image2/identity:${TAG:-latest}
build:
context: .
dockerfile: Identity/Dockerfile
restart: on-failure
environment:
- ASPNETCORE_ENVIRONMENT=Local
- ConnectionStrings__DefaultConnection=Server=postgres2;Port=5432;Uid=postgres;Pwd=Password123;Database=database2
ports:
- "5002:80"
depends_on:
- postgres2
volumes:
- .docker/setup.sql:/docker-entrypoint-initdb.d/setup.sql
- db_data:/var/lib/mysql
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480102.html
