Overview and Introduction
Have you been tempted by .NET Core, but not sure where to start? Well, you’re not the only one, in fact it's actually difficult to find a comprehensive story on "Your first .NET Core API" let alone connect it to Postgres. This quick start aims to provide you a template that can literally be run with 2 commands and provides the opportunity to continue to build out a local application.
The QuickStart provides an API that includes:
- Connectivity to PostgreSQL
- Swagger integration
This demo app will run completely in docker. Simply build the container:
Build will compile the application and move out entrypoint shell script ready for execution. This step is important, we want the DB migrations to run when the container starts but before the applications tries to connect. The migrations will create the tables in the database.
COPY . /app
RUN dotnet tool install --global dotnet-ef
RUN dotnet restore
RUN dotnet build
RUN chmod +x ./entrypoint.sh
CMD /bin/bash ./entrypoint.sh
run_cmd="dotnet run --no-build --urls http://0.0.0.0:5000 -v d"
until dotnet ef database update; do
>&2 echo "Migrations executing"
>&2 echo "DB Migrations complete, starting app."
>&2 echo "Running': $run_cmd"
This will start the two containers. PostgreSQL is completely standard, we simply pass in an environment value which is the password for the database (postgres), the small piece to add here is that init.sql script is also mounted between the host (local machine) and the container. This script is copied to a location that is executed on the start-up of the database container. It is very simple. It will drop the "
Posts" database if it exists and then create it again, so we start fresh. This configuration is located in the "docker-compose.yml" file.
Once the app starts, you can interact at http://localhost:5005/swagger to test out the API.
You can connect to the database as well by connecting to: localhost port 5432 with your favourite tool. I recommend and use DBBeaver: settings are:
If you wish to run the app locally, add a lost host entry. The containers internal DNS knows to resolve database to the postgres (name defined in docker-compse.yml file line 10) container so adding this alias to your hosts file will allow your project in VSCode or Visual Studio to execute and connect to the database.
Or change the connection string in appsettings.Development.json to localhost (from database).
I prefer to use Visual Studio. To run the application locally, simply double click the pgapp.sln file and click Run. Your app will compile and run locally and be alliable on port 5000.
Local url: http://localhost:5000/swagger