# Database connection strings explained for Postgres, MySQL and Redis

> A connection string is a single URL that packs the scheme, user, password, host, port, database name and options an app needs to reach a database.

URL: https://levelrail.com/learn/databases/database-connection-strings-explained/
Updated: 2026-11-27

A database connection string is one URL that tells a driver where the database is and how to log in. For Postgres it looks like `postgresql://app:change-me@db:5432/shop?sslmode=require`. Every part has a job, and most connection failures come down to a wrong host, an unencoded character in the password, or a missing TLS setting.

## How it works

The generic shape is `scheme://user:password@host:port/database?option=value`. The driver splits the URL, opens a TCP connection to the host and port, authenticates with the credentials, selects the database, and applies the options. Frameworks usually read the whole URL from one [environment variable](https://levelrail.com/learn/glossary/#environment-variable)) such as `DATABASE_URL`, so the same code runs on your laptop and on the server with different values.

If you have not set up a server yet, start with [install Postgres and connect with psql](https://levelrail.com/learn/databases/install-postgres-and-connect-with-psql/)). The role in the URL should be a limited one from [Postgres roles and permissions](https://levelrail.com/learn/databases/postgres-roles-and-permissions/)).

## Step 1: Read each part of a Postgres URL

```
postgresql://app:change-me@203.0.113.10:5432/shop?sslmode=require
```

- `postgresql://` is the scheme. Most drivers also accept `postgres://`.
- `app` is the role name and `change-me` is its password. Replace the placeholder with the real one.
- `203.0.113.10` is the host: a DNS name, an IP, a Docker service name, or a Unix socket directory.
- `5432` is the port. Leave it out to use the default 5432.
- `shop` is the database name. If you omit it, many clients use a database with the same name as the user.
- `?sslmode=require` is an option after the question mark. Join several with `&`.

The same information can be written as key-value pairs for `psql` and libpq: `host=203.0.113.10 port=5432 dbname=shop user=app sslmode=require`. The password is better supplied through the `PGPASSWORD` environment variable or a `~/.pgpass` file than on the command line, because command lines show up in process lists.

## Step 2: Encode special characters

Characters with meaning in a URL must be percent-encoded when they appear in the user or password. A password `p@ss/w:rd#1` becomes:

```
p%40ss%2Fw%3Ard%231
```

Common ones: `@` is `%40`, `:` is `%3A`, `/` is `%2F`, `?` is `%3F`, `#` is `%23`, `%` is `%25`, a space is `%20`. The simplest fix is to generate passwords from letters and digits only, which avoids encoding entirely. If a driver reports a strange host name that contains part of your password, an unencoded `@` is almost always the cause.

## Step 3: Pick the right sslmode

`sslmode` controls TLS for Postgres:

| Value | Meaning |
| --- | --- |
| `disable` | Never use TLS |
| `prefer` | Try TLS, fall back to plain (the libpq default) |
| `require` | Use TLS, do not verify the certificate |
| `verify-ca` | Use TLS and check the certificate against a trusted CA |
| `verify-full` | Also check that the host name matches the certificate |

On a private Docker network between two containers on the same host, `disable` is common and acceptable. Over the internet, or between hosts, use at least `require`, and prefer `verify-full` with the CA file set through `sslrootcert`. Hosted databases usually document the value they need. For how certificates work, see [TLS certificates](https://levelrail.com/learn/glossary/#tls-certificate)).

## Step 4: MySQL and Redis strings

MySQL and MariaDB use the same shape with a different scheme and default port:

```
mysql://app:change-me@db:3306/shop
```

Some drivers want options like `?ssl-mode=REQUIRED` or their own syntax, so check the driver docs.

Redis has no user name by default and often no database name. The path is a database number, 0 to 15 on a default config:

```
redis://:change-me@cache:6379/0
rediss://:change-me@cache.example.com:6380/0
```

The empty user before the colon is intentional when only `requirepass` is set. With ACL users, put the name before the colon: `redis://worker:change-me@cache:6379/0`. `rediss://` (two s) means TLS. Redis details are in [Redis basics, persistence and security](https://levelrail.com/learn/databases/redis-basics-persistence-and-security/)).

## Step 5: Choose the host in Docker

Inside a container, `localhost` means that container, not your server and not the database. When app and database run in the same Compose project, they share a [Docker network](https://levelrail.com/learn/glossary/#docker-network)) and each service name resolves as a host name:

```yaml
services:
  app:
    environment:
      DATABASE_URL: postgresql://app:${DB_PASSWORD}@db:5432/shop
  db:
    image: postgres:16
```

Use the container port (5432), not a published host port, because traffic stays on the internal network. If the database runs on the host instead, containers need the host's address on the bridge, not `localhost` (see [bridge vs host networking](https://levelrail.com/learn/docker/bridge-vs-host-networking/))). From the host itself, connect to `127.0.0.1` and the published port.

## Step 6: Keep the string out of your repo

A connection string contains a [secret](https://levelrail.com/learn/glossary/#secret)), so do not commit it. Put it in an environment variable loaded from an untracked `.env` file or your platform's secret store, and read it in code. Details are in [environment variables and secrets](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)). Do not print the full URL in logs. If you log it for debugging, mask the password.

## Check it worked

```bash
psql "postgresql://app:change-me@127.0.0.1:5432/shop" -c "SELECT current_user, current_database();"
```

The output should show `app` and `shop`. For Redis, `redis-cli -u redis://:change-me@127.0.0.1:6379/0 ping` should print `PONG`. For MySQL, `mysql -h 127.0.0.1 -u app -p shop` prompts for the password and opens a session.

## Edge cases and gotchas

- **Passwords with `%`.** A literal percent sign must be written `%25`, or the parser reads it as an escape and fails.
- **`postgres://` versus `postgresql://`.** Both work in libpq. Some older ORMs accept only one, and some need `postgresql+psycopg://` style schemes. Follow the library docs.
- **Unix socket hosts.** For a local socket, the host is a directory path such as `/var/run/postgresql`, usually passed as `host=` rather than in the URL authority.
- **Quotes in `.env` files.** Some loaders keep surrounding quotes as part of the value. If the URL fails only in one place, check for stray quotes.
- **Compose variable expansion.** A `$` in a password is treated as a variable reference in Compose files. Write `$$` for a literal dollar, or avoid the character.
- **Wrong port after publishing.** If you published `127.0.0.1:5433:5432`, host tools use 5433 while containers on the network still use 5432.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `psql: error: could not translate host name "db" to address: Name or service not known` | Running outside the Docker network | Use `127.0.0.1` and the published port from the host |
| `psql: error: connection to server at "localhost" (::1), port 5432 failed: Connection refused` | Nothing listening, or app inside a container | Fix the host and check the server is up |
| `FATAL:  password authentication failed for user "app"` | Wrong or unencoded password | Re-check the secret and percent-encode special characters |
| `FATAL:  database "shop" does not exist` | Wrong name in the path | Check with `\l` and create the database |
| `psql: error: connection to server ... failed: FATAL:  no pg_hba.conf entry ... no encryption` | Server requires TLS | Add `sslmode=require` |
| `server does not support SSL, but SSL was required` | Client set `require` against a server without TLS | Use `sslmode=disable` on trusted private links, or enable TLS on the server |
| `ERROR 1045 (28000): Access denied for user 'app'@'172.18.0.3' (using password: YES)` | MySQL account is limited to another host | Create the user for the right host, see the MySQL lesson |
| `NOAUTH Authentication required.` | Redis has `requirepass` and no password was sent | Add `:password@` to the URL |
| `invalid port number` or odd host in the error | `@`, `:` or `/` in the password not encoded | Percent-encode it |

## Quick reference

```
postgresql://user:password@host:5432/dbname?sslmode=require
mysql://user:password@host:3306/dbname
redis://:password@host:6379/0
rediss://:password@host:6379/0

@ %40   : %3A   / %2F   ? %3F   # %23   % %25
```

## Related lessons

- [Install Postgres and connect with psql](https://levelrail.com/learn/databases/install-postgres-and-connect-with-psql/)): the server these URLs point at.
- [Environment variables and secrets](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)): where to store the finished string.
- [Docker networks explained](https://levelrail.com/learn/docker/docker-networks-explained/)): why service names work as host names.
- [Private networking between services](https://levelrail.com/learn/deploy-operate/private-networking-between-services/)): keep the database off the public internet.
- [Self-hosted Postgres in Docker, connect your app](https://levelrail.com/blog/self-hosted-postgres-docker-connect-app/)): a worked example.

## Next

Continue with [Postgres backup and restore with pg_dump](https://levelrail.com/learn/databases/postgres-backup-and-restore-with-pg-dump/)) to protect the data behind these strings.

## Frequently asked questions

### What is a Postgres connection string?

It is a URL of the form postgresql://user:password@host:5432/dbname?sslmode=require. The libpq library and most drivers accept it.

### How do I put a special character like @ in a database password?

Percent-encode it in the URL, for example @ becomes %40 and / becomes %2F. A raw @ ends the password early and the parser reads the wrong host.

### Why does my app connect to localhost but fail inside Docker?

Inside a container, localhost is the container itself. Use the service name of the database container, such as db, on a shared Docker network.

### What does sslmode=require do?

It makes the client refuse to connect without TLS, but it does not verify the server certificate. verify-full also checks the certificate and host name.


## Sources

- [PostgreSQL documentation, connection strings](https://www.postgresql.org/docs/current/libpq-connect.html)
