Connect to PostgreSQL
Ce contenu n’est pas encore disponible dans votre langue.
When you reference a PostgreSQL resource from the AppHost with WithReference (C#) or withReference (TypeScript), Aspire automatically injects connection information into the consuming application as environment variables. This page shows how to read those variables and connect to PostgreSQL from any language.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called postgresdb becomes POSTGRESDB_URI.
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 server resource 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/catalogConnect from your application
Section titled “Connect from your application”The following examples show how to connect to PostgreSQL from different languages. Each example assumes you have a PostgreSQL database resource named postgresdb referenced from your AppHost.
Install the PostgreSQL client library:
npm install pgRead the injected environment variables and connect:
import pg from 'pg';
// Read Aspire-injected connection propertiesconst client = new pg.Client({ user: process.env.POSTGRESDB_USERNAME, host: process.env.POSTGRESDB_HOST, database: process.env.POSTGRESDB_DATABASENAME, password: process.env.POSTGRESDB_PASSWORD, port: process.env.POSTGRESDB_PORT,});
await client.connect();Or use the connection URI directly:
const client = new pg.Client({ connectionString: process.env.POSTGRESDB_URI,});
await client.connect();Install a PostgreSQL driver. This example uses psycopg:
pip install psycopg[binary]Read the injected environment variables and connect:
import osimport psycopg
# Read the Aspire-injected connection URIpostgres_uri = os.getenv("POSTGRESDB_URI")
async with await psycopg.AsyncConnection.connect( postgres_uri, autocommit=True) as conn: # Use conn to query the database... passUse the pgx driver, the most actively maintained and feature-rich PostgreSQL driver for Go:
go get github.com/jackc/pgx/v5Note:
lib/pqis another popular Go PostgreSQL driver, butpgxis recommended for new projects because it offers better performance, native PostgreSQL protocol support, and active maintenance.
Read the injected environment variables and connect:
package main
import ( "context" "os" "github.com/jackc/pgx/v5")
func main() { // Read the Aspire-injected connection URI connStr := os.Getenv("POSTGRESDB_URI")
conn, err := pgx.Connect(context.Background(), connStr) if err != nil { panic(err) } defer conn.Close(context.Background())}For .NET applications, the recommended approach is to use the Client integration (.NET), which provides automatic dependency injection, health checks, and telemetry.
If you prefer to connect using environment variables directly:
var connectionString = Environment.GetEnvironmentVariable( "POSTGRESDB_URI");
await using var dataSource = NpgsqlDataSource.Create(connectionString!);await using var conn = await dataSource.OpenConnectionAsync();Passing custom environment variables from the AppHost
Section titled “Passing custom environment variables from the AppHost”If your application expects specific environment variable names, you can pass individual connection properties from the AppHost:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var database = postgres.AddDatabase("myDatabase");
var app = builder.AddExecutable("my-app", "node", "app.js", ".") .WithReference(database) .WithEnvironment(context => { 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();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const postgres = await builder.addPostgres("postgres");const database = await postgres.addDatabase("myDatabase");
await builder.addNodeApp("my-app", "./app", "index.js") .withReference(database) .withEnvironment("POSTGRES_USER", postgres.userName) .withEnvironment("POSTGRES_PASSWORD", postgres.password) .withEnvironment("POSTGRES_DATABASE", "myDatabase");
await builder.build().run();