I’ve been playing recently with ASP.Net Core and I’m developing a small Web API project in order to teach myself the framework.
In still article I’ll explain how to use a Postgres database with Docker, in order to make your development experience much more enjoyable.
Before moving on, please make sure that you’ve installed:
First, create the docker-compose.yml
file in your root directory of the project, the file should contain:
version: ‘3.4’ services: postgres: image: postgres environment: - POSTGRES_USER=app - POSTGRES_PASSWORD=app - POSTGRES_DB=mydbname volumes: - ./volumes/data/db:/var/lib/postgresql/data ports: - 5432:5432
This specific postgres configuration passes some self-explanatory environments variables to the postgres database, it binds the ./volumes/data directory to the postgres’ data volume and it exposes the port 5432. We bind the volume so we can achieve data persistency and explore the files generated by the postgres database.
Next, add the following packages to your ASP.Net Core application:
<pre class="wp-block-code">```
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL.Design
Add your database connection configuration to the `appsettings.Development.json` file, note that they match the strings from the `docker-compose.yml` file. When running in production you should deploy each service in a separate container and configure them with environment variables. Never hardcode sensitive information in your files!
{
"DatabaseConfig": {
"PostgresSQL": "Server=localhost;Port=5432;Database=mydbname;User Id=app;Password=app;"
},
...
}
Now in the `Startup.cs` file, when configuring the application context, specify that you want to use PostgresSQL.
services.AddDbContext
(options =>
{
options.UseNpgsql(Configuration.GetSection("DatabaseConfig")["PostgresSQL"]);
});
This is it! Make sure that your application is not running and start the database with `docker-compose up`. After the database has started open a new terminal and add the migrations:
dotnet ef migrations add InitialMigration
dotnet ef database update
If you’d like to stop the database you can run `docker ps` and `docker stop
` where `` is the hash of your database container. Following the steps from above gives you an isolated development database that you can use alongside your ASP.Net Core application, if you need to add ElasticSearch, Redis or another service all you need to do is change the `docker-compose.yml` file to include them and voilà.
Thank you for reading, have a nice day!