First of all, I'm sorry for my English.
I am developing an ASP.NET Core Web API, and I am working with a friend. To work together comfortably I wanted to set up a Docker with our API, and a database running. And I have problem with Entity Framework.
Here is the problem, the name of the container for Postgres is postgres_image
, so the connection string to connect to it from the api is:
"Host=postgres_image;Port=5432;Database=grdedb;Username=postgres;Password=postgres"
And it is working. But when I want to create an Entity Framework migration to the database located in the Docker container, it doesn't work; I have to change the host to localhost.
But when I change it the migration works and after that it is the API which stops.
Thank you very much for your help
My docker compose file
version: '3.4'
networks:
grdeapi-dev:
driver: bridge
services:
grdeapi:
image: grdeapi
build:
context: .
dockerfile: ./Dockerfile
ports:
- 5101:5101
networks:
- grdeapi-dev
postgres_image:
image: postgres:latest
ports:
- 5432:5432
restart: always
volumes:
- db_volume:/var/lib/postgresql/data
environment:
POSTGRES_USER: "postgres"
POSTGRES_PASSWORD: "postgres"
POSTGRES_DB: "grdedb"
networks:
- grdeapi-dev
volumes:
db_volume:
My connection string
"Host=postgres_image;Port=5432;Database=grdedb;Username=postgres;Password=postgres"
And the error I get from the entity framework
Failed to connect to 212.95.74.75:5432
Entity framework works when I change the host to localhost, but then my dotnet api can't connect to my database.
CodePudding user response:
Have a config for running in Docker, and one for running in development.
In the former (name it appsettings.Development.Docker.json
for example) configure your connection string with the Docker hostname ("postgres_image"), and locally (when running from Visual Studio or when running migrations against said database server) just use "localhost". Name the latter appsettings.Development.json
.
Then adjust your DOTNET_ENVIRONMENT accordingly:
services:
grdeapi:
DOTNET_ENVIRONMENT: "Development.Docker"