Chapter 9 · Lesson 3 of 8
Databases and data

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.

By the end you will

Write a correct connection string for Postgres, MySQL or Redis, encode special characters, and choose the right host inside Docker.

Time
15 min
Level
Beginner
Check
4 questions
You need
  • A database you can reach, or the details of one

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 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. The role in the URL should be a limited one from Postgres roles and permissions.

Step 1: Read each part of a Postgres URL#

output
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:

output
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:

ValueMeaning
disableNever use TLS
preferTry TLS, fall back to plain (the libpq default)
requireUse TLS, do not verify the certificate
verify-caUse TLS and check the certificate against a trusted CA
verify-fullAlso 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.

Step 4: MySQL and Redis strings#

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

output
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:

output
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.

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 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). 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, 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. 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#

SymptomLikely causeFix
psql: error: could not translate host name "db" to address: Name or service not knownRunning outside the Docker networkUse 127.0.0.1 and the published port from the host
psql: error: connection to server at "localhost" (::1), port 5432 failed: Connection refusedNothing listening, or app inside a containerFix the host and check the server is up
FATAL: password authentication failed for user "app"Wrong or unencoded passwordRe-check the secret and percent-encode special characters
FATAL: database "shop" does not existWrong name in the pathCheck with \l and create the database
psql: error: connection to server ... failed: FATAL: no pg_hba.conf entry ... no encryptionServer requires TLSAdd sslmode=require
server does not support SSL, but SSL was requiredClient set require against a server without TLSUse 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 hostCreate the user for the right host, see the MySQL lesson
NOAUTH Authentication required.Redis has requirepass and no password was sentAdd :password@ to the URL
invalid port number or odd host in the error@, : or / in the password not encodedPercent-encode it

Quick reference#

output
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

Next#

Continue with Postgres backup and restore with pg_dump to protect the data behind these strings.

Check what you learned4 questions
1In postgresql://app:pw@db:5432/shop, what is shop?
2A password contains @. What must you do in the URL?
3Your app runs in Compose with a service named db. Which host works for the app container?
4Which URL scheme means Redis over TLS?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios