The same build should run on a laptop, in staging and in production. What changes between them is configuration: database addresses, API keys, feature switches. The twelve-factor app methodology gives clear rules for this.
Config is not code
Configuration is anything likely to differ between deploys. Do not hard-code it, and do not keep production values in the repository. A good test: could you open-source the codebase right now without leaking a credential?
Use environment variables
Environment variables are language-neutral, easy to change per deployment and hard to commit by accident.
export DATABASE_URL="postgres://app:[email protected]:5432/app"
export LOG_LEVEL="info"
./bin/start-serverimport os
DATABASE_URL = os.environ["DATABASE_URL"] # fail fast if missing
LOG_LEVEL = os.environ.get("LOG_LEVEL", "info") # optional with a defaultFail fast. Read required settings at startup and stop with a clear message when one is missing or invalid. A service that boots with a half-broken configuration fails later, in a confusing way.
Secrets deserve more care
Environment variables are convenient but visible to anything that can read the process or its container definition. Keep secrets in a secret manager or encrypted store, inject them at deploy time, rotate them, and never print them in logs. Keep a record of who changed what and when.
Dev and production parity
Differences between environments cause bugs that only appear in production. Reduce the gaps:
- Use the same type of database and the same major version everywhere.
- Deploy the same artifact, for example one container image, to every environment.
- Keep the time between writing code and deploying it short.
Pitfalls
- Config files per environment that slowly drift apart.
- Code that checks
if production?all over the place. Prefer an explicit setting for each behaviour. - Defaults that are unsafe, such as debug mode on.
Takeaway
One build, many configurations. Keep secrets out of the repository, validate settings at startup and keep environments as alike as you can.
Comments