How does an application connect to a database, and how should connection details be passed?
Short answer
An application connects using a connection string (or database URL) that contains the host, port, database name, username and password. These values must be passed through environment variables or secrets — never hard-coded in the code or baked into the Docker image.
What a connection string looks like
| Stack | Example |
|---|---|
| Java (JDBC) | jdbc:mysql://db.internal:3306/orders |
| Node.js / Python | postgresql://app_user:[email protected]:5432/orders |
| MongoDB | mongodb://app_user:PASSWORD@mongo:27017/orders?authSource=admin |
| .NET | Server=db.internal;Database=orders;User Id=app_user;Password=PASSWORD; |
Every one has the same parts: where (host and port), which database, and who (username and password).
Why environment variables?
The same container image runs in dev, staging and production — only the database changes. So the app reads its settings when it starts:
// Node.js
const pool = new Pool({
host: process.env.DB_HOST,
port: process.env.DB_PORT || 5432,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
});
# Python
import os
DATABASE_URL = os.environ["DATABASE_URL"]
Example — passing it in Docker and Kubernetes
docker run -e DB_HOST=db -e DB_USER=app -e DB_PASSWORD='s3cret' orders-api:1.0
# Kubernetes: password from a Secret, not plain text in the Deployment
env:
- name: DB_HOST
value: postgres.db.svc.cluster.local
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: orders-db
key: password
In the cloud, passwords often live in AWS Secrets Manager or Azure Key Vault, synced into Kubernetes with tools like the External Secrets Operator.
What to say in the interview
"Apps connect through a connection string with host, port, database, user and password. We never hard-code it. Non-secret values come from environment variables or ConfigMaps, and passwords from Kubernetes Secrets or a vault like AWS Secrets Manager. That way the same image runs in every environment, and rotating a password doesn't need a rebuild."
Follow-up questions you may get
- What is connection pooling? Reusing a set of open connections instead of opening a new one per request — faster and protects the database from too many connections.
- What are database migrations? Versioned scripts (Flyway, Liquibase, Alembic) that create or change tables automatically when the app is deployed.