PostgreSQL Hosting integration
To get started with the Aspire PostgreSQL integrations, follow the Get started with PostgreSQL integrations guide. If you want to learn how to use the PostgreSQL Entity Framework Core (EF Core) client integration, see Get started with the PostgreSQL Entity Framework Core integrations.
This article includes full details on the Aspire PostgreSQL Hosting integration, which allows you to model PostgreSQL server and database resources in your AppHost project.
Installation
Section titled “Installation”The PostgreSQL hosting integration models various PostgreSQL resources as the following types.
PostgresServerResourcePostgresDatabaseResourcePostgresPgAdminContainerResourcePostgresPgWebContainerResource
To access these types and APIs for expressing them as resources in your AppHost project, install the 📦 Aspire.Hosting.PostgreSQL NuGet package:
aspire add postgresqlThe Aspire CLI is interactive, be sure to select the appropriate search result when prompted:
Select an integration to add:
> postgresql (Aspire.Hosting.PostgreSQL)> Other results listed as selectable options...#:package Aspire.Hosting.PostgreSQL@*<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="*" />Add PostgreSQL server resource
Section titled “Add PostgreSQL server resource”In your AppHost project, call AddPostgres on the builder instance to add a PostgreSQL server resource then call AddDatabase on the postgres instance to add a database resource as shown in the following example:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>("apiservice") .WithReference(postgresdb);
// After adding all resources, run the app...-
When Aspire adds a container image to the app host, as shown in the preceding example with the
docker.io/library/postgresimage, it creates a new PostgreSQL server instance on your local machine. A reference to your PostgreSQL server and database instance (thepostgresdbvariable) are used to add a dependency to theExampleProject. -
When adding a database resource to the app model, the database is created if it doesn’t already exist. The creation of the database relies on the AppHost eventing APIs, specifically
ResourceReadyEvent. In other words, when thepostgresresource is ready, the event is raised and the database resource is created. -
The PostgreSQL server resource includes default credentials with a
usernameof"postgres"and randomly generatedpasswordusing theCreateDefaultPasswordParametermethod. -
The
WithReferencemethod configures a connection in theExampleProjectnamed"messaging".
Add PostgreSQL resource with database scripts
Section titled “Add PostgreSQL resource with database scripts”By default, when you add a PostgresDatabaseResource, it relies on the following script to create the database:
CREATE DATABASE "<QUOTED_DATABASE_NAME>"To alter the default script, chain a call to the WithCreationScript method on the database resource builder:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");
var databaseName = "app_db";var creationScript = $$""" -- Create the database CREATE DATABASE {{databaseName}};
""";
var db = postgres.AddDatabase(databaseName) .WithCreationScript(creationScript);
builder.AddProject<Projects.ExampleProject>() .WithReference(db) .WaitFor(db);
// After adding all resources, run the app...The preceding example creates a database named app_db. The script is run when the database resource is created. The script is passed as a string to the WithCreationScript method, which is then run in the context of the PostgreSQL resource.
Add PostgreSQL pgAdmin resource
Section titled “Add PostgreSQL pgAdmin resource”When adding PostgreSQL resources to the builder with the AddPostgres method, you can chain calls to WithPgAdmin to add the dpage/pgadmin4 container. This container is a cross-platform client for PostgreSQL databases, that serves a web-based admin dashboard. Consider the following example:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithPgAdmin();
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...The preceding code adds a container based on the docker.io/dpage/pgadmin4 image. The container is used to manage the PostgreSQL server and database resources. The WithPgAdmin method adds a container that serves a web-based admin dashboard for PostgreSQL databases.
Configure the pgAdmin host port
Section titled “Configure the pgAdmin host port”To configure the host port for the pgAdmin container, call the WithHostPort method on the PostgreSQL server resource. The following example shows how to configure the host port for the pgAdmin container:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithPgAdmin(pgAdmin => pgAdmin.WithHostPort(5050));
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...The preceding code adds and configures the host port for the pgAdmin container. The host port is otherwise randomly assigned.
Add PostgreSQL pgWeb resource
Section titled “Add PostgreSQL pgWeb resource”When adding PostgreSQL resources to the builder with the AddPostgres method, you can chain calls to WithPgWeb to add the sosedoff/pgweb container. This container is a cross-platform client for PostgreSQL databases, that serves a web-based admin dashboard. Consider the following example:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithPgWeb();
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...The preceding code adds a container based on the docker.io/sosedoff/pgweb image. All registered PostgresDatabaseResource instances are used to create a configuration file per instance, and each config is bound to the pgweb container bookmark directory. For more information, see PgWeb docs: Server connection bookmarks.
Configure the pgWeb host port
Section titled “Configure the pgWeb host port”To configure the host port for the pgWeb container, call the WithHostPort method on the PostgreSQL server resource. The following example shows how to configure the host port for the pgAdmin container:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithPgWeb(pgWeb => pgWeb.WithHostPort(5050));
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...The preceding code adds and configures the host port for the pgWeb container. The host port is otherwise randomly assigned.
Add PostgreSQL server resource with data volume
Section titled “Add PostgreSQL server resource with data volume”To add a data volume to the PostgreSQL server resource, call the WithDataVolume method on the PostgreSQL server resource:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithDataVolume(isReadOnly: false);
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...The data volume is used to persist the PostgreSQL server data outside the lifecycle of its container. The data volume is mounted at the /var/lib/postgresql/data path in the PostgreSQL server container and when a name parameter isn’t provided, the name is generated at random. For more information on data volumes and details on why they’re preferred over bind mounts, see Docker docs: Volumes.
Add PostgreSQL server resource with data bind mount
Section titled “Add PostgreSQL server resource with data bind mount”To add a data bind mount to the PostgreSQL server resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithDataBindMount( source: "/PostgreSQL/Data", isReadOnly: false);
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...Data bind mounts rely on the host machine’s filesystem to persist the PostgreSQL server data across container restarts. The data bind mount is mounted at the C:\PostgreSQL\Data on Windows (or /PostgreSQL/Data on Unix) path on the host machine in the PostgreSQL server container. For more information on data bind mounts, see Docker docs: Bind mounts.
Add PostgreSQL server resource with init bind mount
Section titled “Add PostgreSQL server resource with init bind mount”To add an init bind mount to the PostgreSQL server resource, call the WithInitBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithInitBindMount(@"C:\PostgreSQL\Init");
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...The init bind mount relies on the host machine’s filesystem to initialize the PostgreSQL server database with the containers init folder. This folder is used for initialization, running any executable shell scripts or .sql command files after the postgres-data folder is created. The init bind mount is mounted at the C:\PostgreSQL\Init on Windows (or /PostgreSQL/Init on Unix) path on the host machine in the PostgreSQL server container.
Add PostgreSQL server resource with parameters
Section titled “Add PostgreSQL server resource with parameters”When you want to explicitly provide the username and password used by the container image, you can provide these credentials as parameters. Consider the following alternative example:
var builder = DistributedApplication.CreateBuilder(args);
var username = builder.AddParameter("username", secret: true);var password = builder.AddParameter("password", secret: true);
var postgres = builder.AddPostgres("postgres", username, password);var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(postgresdb);
// After adding all resources, run the app...Connection properties
Section titled “Connection properties”When you reference a PostgreSQL resource using WithReference, the following connection properties are made available to the consuming project:
PostgreSQL server
Section titled “PostgreSQL server”The PostgreSQL server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the PostgreSQL server |
Port | The port number the PostgreSQL server is listening on |
Username | The username for authentication |
Password | The password for authentication |
Uri | The connection URI in postgresql:// format, with the format postgresql://{Username}:{Password}@{Host}:{Port} |
JdbcConnectionString | JDBC-format connection string, with the format jdbc:postgresql://{Host}:{Port}. User and password credentials are provided as separate Username and Password properties. |
Example connection strings:
Uri: postgresql://postgres:p%40ssw0rd1@localhost:5432JdbcConnectionString: jdbc:postgresql://localhost:5432PostgreSQL database
Section titled “PostgreSQL database”The PostgreSQL database resource inherits all properties from its parent PostgresServerResource and adds:
| Property Name | Description |
|---|---|
Uri | The connection URI with the database name, with the format postgresql://{Username}:{Password}@{Host}:{Port}/{DatabaseName} |
JdbcConnectionString | JDBC connection string with database name, with the format jdbc:postgresql://{Host}:{Port}/{DatabaseName}. User and password credentials are provided as separate Username and Password properties. |
DatabaseName | The name of the database |
Example connection strings:
Uri: postgresql://postgres:p%40ssw0rd1@localhost:5432/catalogJdbcConnectionString: jdbc:postgresql://localhost:5432/catalogHosting integration health checks
Section titled “Hosting integration health checks”The PostgreSQL hosting integration automatically adds a health check for the PostgreSQL server resource. The health check verifies that the PostgreSQL server is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.Npgsql NuGet package.
Using with non-.NET applications
Section titled “Using with non-.NET applications”The PostgreSQL hosting integration can be used with any application technology, not just .NET applications. When you use WithReference to reference a PostgreSQL resource, connection information is automatically injected as environment variables into the referencing application.
For applications that don’t use the client integration, you can access the connection information through environment variables. Here’s an example of how to configure environment variables for a non-.NET application:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithLifetime(ContainerLifetime.Persistent);
var database = postgres.AddDatabase("myDatabase");
// Example: Configure a non-.NET application with PostgreSQL accessvar app = builder.AddExecutable("my-app", "node", "app.js", ".") .WithReference(database) // Provides ConnectionStrings__myDatabase .WithEnvironment(context => { // Additional individual connection details as environment variables context.EnvironmentVariables["POSTGRES_HOST"] = postgres.Resource.PrimaryEndpoint.Property(EndpointProperty.Host); context.EnvironmentVariables["POSTGRES_PORT"] = postgres.Resource.PrimaryEndpoint.Property(EndpointProperty.Port); context.EnvironmentVariables["POSTGRES_USER"] = postgres.Resource.UserNameParameter; context.EnvironmentVariables["POSTGRES_PASSWORD"] = postgres.Resource.PasswordParameter; context.EnvironmentVariables["POSTGRES_DATABASE"] = database.Resource.DatabaseName; });
builder.Build().Run();This configuration provides the non-.NET application with several environment variables:
ConnectionStrings__myDatabase: The complete PostgreSQL connection stringPOSTGRES_HOST: The hostname/IP address of the PostgreSQL serverPOSTGRES_PORT: The port number the PostgreSQL server is listening onPOSTGRES_USER: The database usernamePOSTGRES_PASSWORD: The dynamically generated passwordPOSTGRES_DATABASE: The name of the database
Your non-.NET application can then read these environment variables to connect to the PostgreSQL database using the appropriate database driver for that technology (for example, psycopg2 for Python, pg for Node.js, or pq for Go).