I have a postgis database running using the following docker-compose file:
version: '3.9'
volumes:
dbbackups:
postgis-data:
services:
db:
image: kartoza/postgis:14-3.2
volumes:
- postgis-data:/var/lib/postgresql
- dbbackups:/backups
environment:
# If you need to create multiple database you can add coma separated databases eg gis,data
- POSTGRES_DB=my_db
- POSTGRES_USER=my_username
- POSTGRES_PASS=my_password
- ALLOW_IP_RANGE=0.0.0.0/0
# Add extensions you need to be enabled by default in the DB. Default are the five specified below
- POSTGRES_MULTIPLE_EXTENSIONS=postgis,hstore,postgis_topology,postgis_raster,pgrouting
ports:
- "25432:5432"
restart: on-failure
healthcheck:
test: "exit 0"
I have an ASP.Net Core Web API project configured to use this database. In Program.cs
:
builder.Services.AddDbContext<PerceptionAnnotationServerContext>(options =>
options.UseNpgsql("Host=localhost;Port=25432;Database=my_db;Username=my_username;Password=my_password"));
If I do Get-Migration
or Add-Migration
then Update-Database
from the VS 2022 pack manager console, I get the error:
An error occurred while accessing the database. Continuing without the information provided by the database. Error: 28000: role "my_username" does not exist
I initially found this answer on how to add the user. However checking with pgAdmin shows that the role "my_username" already exists and has access to "my_db".
Any ideas?
CodePudding user response:
I had forgotten to add to the db context:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=localhost;Port=25432;Database=my_db;Username=my_username;Password=my_password");
}
CodePudding user response:
The database connection string with the Host=Localhost is what you used on your local environment. Inside the container application the networking are different. You should see how the containers do the networking https://docs.docker.com/network/.
What you need to change in your connection string is to point it to the name of you service which is db. You can also add a custom name for your container like this container_name: myContainerDB and use the myContainerDB as the Host in your connection string.
Edit:
This only applies if your application is running in a container. May I know if it is?