I. What Are Environment Variables and a Runtime Environment?
A program does not run under completely isolated conditions. It usually depends on the operating system, runtime, configuration files, network services, databases, file systems, and other external resources.
Together, these external conditions form the program's runtime environment.
Within a runtime environment, environment variables are a very common mechanism for passing configuration.
1. What Are Environment Variables?
Environment variables are a set of key-value pairs in the operating system's process environment, used to pass configuration information to a program and its child processes.
For example:
APP_ENV=production
PORT=8080
LOG_LEVEL=info
DATABASE_HOST=127.0.0.1
Here:
APP_ENV: the current application environment.PORT: the port the application listens on.LOG_LEVEL: the log level.DATABASE_HOST: the database host address.
When the program starts, it can read these variables and adjust its behavior according to the different configurations.
For example, the same program can connect to different databases through different environment variables without modifying the source code.
2. What Is a Runtime Environment?
A runtime environment is the collection of software, system configuration, and resource conditions that a program depends on in order to execute.
It usually includes:
- The operating system and its version.
- The CPU architecture.
- The programming language runtime.
- The virtual machine or interpreter.
- System libraries and dynamic link libraries.
- Environment variables.
- Configuration files.
- The network and file system.
- External services such as databases and message queues.
- User permissions and security policies.
For example, the runtime environment of a Java web application might include:
Linux
├── JDK 17
├── Spring Boot Application
├── JVM Parameters
├── Environment Variables
├── Database Connection Configuration
├── Logging Configuration
└── Network and File System
Environment variables are only one part of the runtime environment; the two are not equivalent.
3. The Relationship Between Environment Variables and the Runtime Environment
| Comparison Dimension | Environment Variables | Runtime Environment |
|---|---|---|
| Nature | Key-value configuration | The set of conditions for program execution |
| Role | Pass external information to the program | Provide the conditions required for program execution |
| Content | Variables in string form | Operating system, runtime, configuration, resources, etc. |
| Lifecycle | Usually tied to the process and its environment | Depends on the lifecycle of the system and runtime resources |
| Management | Shell, system services, containers, CI/CD | Operating system, runtime, containers, deployment platforms |
| Typical Examples | PATH, PORT, APP_ENV |
Linux, JVM, Node.js, databases |
The relationship between the two can be summarized as:
flowchart TD
A["Runtime Environment"] --> B["Operating System"]
A --> C["Language Runtime"]
A --> D["System Dependencies and Resources"]
A --> E["Configuration Management"]
E --> F["Environment Variables"]
E --> G["Configuration Files"]
F --> H["Application"]
G --> H
B --> H
C --> H
D --> H
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
II. The Basic Principles of Environment Variables
Environment variables are not a set of global variables created at will by the application itself; they are a process environment mechanism provided by the operating system.
In Unix-like systems, a process can usually access environment variables through an array of environment strings.
1. How Environment Variables Are Stored
Environment variables usually take the following form:
KEY=VALUE
For example:
PATH=/usr/local/bin:/usr/bin:/bin
HOME=/home/user
LANG=zh_CN.UTF-8
Here:
KEYis the variable name.VALUEis the variable value.=separates the name from the value.
Environment variable values are usually passed as strings.
Even when a variable represents a number, a boolean, or a path, the program usually has to parse it itself after reading it.
For example:
PORT=8080
DEBUG=true
After reading them, the program has to decide:
- Whether
PORTshould be converted to an integer. - By what rules
DEBUGshould be parsed as a boolean. - What default value to use when the configuration is missing.
2. Process Environment
In Unix-like systems, a process can have its own set of environment variables.
When a process starts, the operating system passes the environment information to the new program.
In C, you can access environment variables through environ or getenv().
Example:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *env = getenv("APP_ENV");
if (env != NULL) {
printf("Environment: %s\n", env);
} else {
printf("APP_ENV is not set\n");
}
return 0;
}
Run:
APP_ENV=production ./app
Output:
Environment: production
Here, APP_ENV=production only affects the process started this time and the environment it subsequently passes on; it does not automatically modify the environment variables of every process in the system.
3. Environment Variable Inheritance Between Parent and Child Processes
When a process is created, the child process can usually inherit the parent process's environment variables.
In Unix/Linux, the typical case is:
- The shell holds the current environment variables.
- The shell starts a child process.
- The child process receives a copy of the environment variables.
- The child process reads its own environment variables.
- If the child process modifies environment variables, it does not modify the parent process's environment in return.
Example:
export APP_ENV=development
python app.py
The Python process can read APP_ENV.
If the Python program modifies environment variables internally, it usually does not change the shell environment that started it.
flowchart TD
A["Shell process"] --> B["Set APP_ENV=development"]
B --> C["Start child process"]
C --> D["Child process inherits environment variables"]
D --> E["Read environment variables"]
E --> F["Modify child process environment"]
F --> G["Child process environment changes"]
G --> H["Parent process environment remains unchanged"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that the exact implementation of environment variable inheritance depends on the operating system.
In Windows, a process also has its own environment block, and a child process can receive the corresponding environment configuration when it is created.
4. Scope of Environment Variables
Environment variables can have different scopes depending on how they are set.
| Setting method | Scope | Example |
|---|---|---|
| Temporary assignment before a command | Usually affects only this command and its child processes | APP_ENV=prod app |
| Ordinary Shell variable | Current Shell | APP_ENV=prod |
| Exported Shell variable | Current Shell and child processes started afterward | export APP_ENV=prod |
| User-level configuration | Sessions related to the user's login or startup | Shell configuration file |
| System-level configuration | System services or related processes | System environment configuration |
| Container environment configuration | Processes inside the container | Docker ENV |
| CI/CD configuration | Pipeline tasks or jobs | CI Variables |
Not every setting automatically affects processes that are already running.
In most cases, a process has its own set of environment variables once it starts. Modifying Shell configuration files or system configuration will not automatically refresh the environment of existing processes.
III. Common Types of Environment Variables
Environment variables can be classified by purpose.
1. System Environment Variables
System environment variables are usually used to configure the operating system and command-line tools.
Common variables:
| Variable | Purpose | Common systems |
|---|---|---|
PATH |
Command search path | Linux, macOS, Windows |
HOME |
User home directory | Linux, macOS |
USER |
Current username | Common Unix systems |
SHELL |
User's default Shell | Common Unix systems |
LANG |
Default language and locale settings | Linux, macOS |
TMPDIR |
Temporary directory | Unix systems |
TEMP |
Temporary file directory | Windows and others |
SystemRoot |
Windows system directory | Windows |
USERPROFILE |
Windows user profile directory | Windows |
The variable names and semantics are not exactly the same across different operating systems.
2. The PATH Environment Variable
PATH is one of the most common and most important environment variables.
It specifies the directories in which the system searches for executable programs.
For example:
echo "$PATH"
Possible output:
/usr/local/bin:/usr/bin:/bin
When a user runs:
python
The Shell typically searches for the corresponding executable in the order of the directories listed in PATH.
If multiple programs with the same name exist in different directories, the one found earlier in the search order usually takes precedence.
For example:
export PATH="/opt/python/bin:$PATH"
This places /opt/python/bin ahead of the existing search path.
To check a command's location:
which python
In scripts where reliability matters more, you can also use:
command -v python
In Windows, PATH uses semicolons to separate paths, while Unix-like systems typically use colons.
3. Application Environment Variables
Applications can define their own environment variables.
For example:
APP_ENV
APP_PORT
APP_DEBUG
APP_LOG_LEVEL
APP_CONFIG_PATH
These variables are usually used to control:
- The application's run mode.
- The port the service listens on.
- The log output level.
- Feature toggles.
- The configuration file path.
- External service addresses.
Applications should clearly specify variable names, data types, default values, and validation rules to avoid ambiguous configuration meanings.
4. Sensitive Information Environment Variables
Some environment variables may be used to pass sensitive information:
DATABASE_PASSWORD
API_TOKEN
JWT_SECRET
PRIVATE_KEY
Although environment variables are often used to pass secrets, they are not a dedicated secrets management system.
Environment variables may appear in:
- In process information or debug information.
- In crash dumps.
- In diagnostic logs.
- In CI/CD logs.
- In container configuration and management interfaces.
- In error output.
Therefore, environment variables should not be regarded as an inherently secure storage method.
In production environments, dedicated secret management services, controlled Secret injection mechanisms, or the secure credential management capabilities provided by the operating system should be preferred.
IV. How to Set and Read Environment Variables?
Different operating systems and programming languages provide different ways to manage environment variables.
1. Linux / macOS
View variables:
echo "$APP_ENV"
Set a variable in the current Shell:
APP_ENV=development
Export an environment variable:
export APP_ENV=production
Delete an environment variable:
unset APP_ENV
Set a variable for a single command:
APP_ENV=test python app.py
This syntax usually affects only the current command and its child processes, and does not permanently modify the Shell configuration.
2. Windows CMD
View variables:
echo %APP_ENV%
Set a variable for the current command-line session:
set APP_ENV=production
Delete a variable:
set APP_ENV=
The setting is valid only for the current CMD session and is usually not retained after the window is closed.
3. Windows PowerShell
Read:
$env:APP_ENV
Set:
$env:APP_ENV = "production"
Delete:
Remove-Item Env:APP_ENV
The setting affects only the current PowerShell process and child processes launched afterward; it is not the same as permanently modifying system environment variables.
4. Reading Environment Variables in Python
Python can use os.environ to access environment variables.
import os
app_env = os.environ.get(
"APP_ENV",
"development"
)
port = int(
os.environ.get("PORT", "8000")
)
print(app_env)
print(port)
Here:
os.environ: Access process environment variables.get(): Read a variable and support a default value.int(): Convert a string to an integer.
Set an environment variable:
import os
os.environ["APP_ENV"] = "production"
This modifies the environment variable set of the current Python process and does not automatically modify the parent process environment.
5. Reading Environment Variables in Java
Java can read environment variables through System.getenv().
public class Main {
public static void main(String[] args) {
String appEnv =
System.getenv("APP_ENV");
String port =
System.getenv("PORT");
System.out.println(appEnv);
System.out.println(port);
}
}
Read a single variable:
String value = System.getenv("APP_ENV");
Get all environment variables:
Map<String, String> env =
System.getenv();
The Java standard API provides the ability to read environment variables, but it does not provide a standard interface for modifying the current process's environment variables through System.getenv().
6. Reading Environment Variables in JavaScript / Node.js
Node.js uses process.env to access environment variables.
const appEnv =
process.env.APP_ENV || "development";
const port =
Number(process.env.PORT || 3000);
console.log(appEnv);
console.log(port);
Set the variable:
process.env.APP_ENV = "production";
This changes the environment variable object in the current Node.js process and does not affect the parent process’s environment.
Also note that values in process.env are generally handled as strings; the application should perform its own type conversion and validation.
7. Reading Environment Variables in Go
Go uses os.Getenv() and os.LookupEnv().
package main
import (
"fmt"
"os"
)
func main() {
appEnv := os.Getenv("APP_ENV")
port, exists := os.LookupEnv("PORT")
fmt.Println(appEnv)
fmt.Println(port, exists)
}
The difference between the two methods:
os.Getenv(): returns an empty string when the variable does not exist.os.LookupEnv(): additionally returns whether the variable exists.
This distinction is very important for determining whether a variable has been explicitly configured.
8. Reading Environment Variables in Rust
The Rust standard library provides the std::env module.
use std::env;
fn main() {
let app_env = env::var("APP_ENV")
.unwrap_or_else(|_| {
"development".to_string()
});
println!("{}", app_env);
}
The result of reading may contain an error, for example if the variable does not exist or its value cannot be converted into a valid Unicode string.
Production code should decide how to handle these errors based on the specific business requirements.
V. Composition of the Runtime Environment
The runtime environment includes not only the operating system but also the entire software and resource system on which program execution depends.
1. Operating System Environment
The operating system provides the basic runtime capabilities for programs.
It mainly includes:
- Process management.
- Thread scheduling.
- Memory management.
- File system.
- Network communication.
- Permission control.
- System call interfaces.
For example, Linux, Windows, and macOS can all run Java programs, but they differ in file paths, process management, system calls, and dynamic linking mechanisms.
2. Programming Language Runtime
Different languages usually require different runtime support.
| Language | Common Runtime Environment | Main Responsibilities |
|---|---|---|
| Java | JVM | Bytecode execution, memory management, garbage collection |
| Python | CPython and other implementations | Interpreted execution, object management, module loading |
| JavaScript | V8, SpiderMonkey, etc. | JavaScript execution, optimizing compilation, garbage collection |
| .NET | CLR | IL execution, JIT, garbage collection |
| Go | Go Runtime | Scheduling, memory management, garbage collection |
| Rust | Native executables and standard library | Provides language libraries and runtime support |
Note that a language runtime is not necessarily a separate virtual machine process.
For example, Go programs usually link the relevant Go Runtime code into the generated executable, while Java programs usually run on top of the JVM.
3. System Dependencies and Dynamic Link Libraries
A program may depend on dynamic libraries provided by the operating system.
For example:
.sofiles on Linux..dllfiles on Windows..dylibfiles on macOS.
If a dynamic library that the program depends on is missing, loading may fail.
On Linux, you can use:
ldd ./app
to inspect dynamic dependencies.
For untrusted binary files, using ldd directly carries security risks. To statically inspect ELF dynamic dependencies, consider:
readelf -d ./app
4. External Service Environment
Modern applications usually depend on other services:
- Databases such as MySQL and PostgreSQL.
- Caching systems such as Redis.
- Message queues such as Kafka and RabbitMQ.
- Object storage services.
- Third-party APIs.
- Identity authentication services.
These services may be located on the local machine, on a LAN, in a cloud platform, or in other containers.
Therefore, the application runtime environment is not only the local software environment but also includes the accessibility of external services, network connectivity, and authentication configuration.
5. Hierarchy of the Runtime Environment
flowchart TD
A["Application"] --> B["Language runtime"]
B --> C["System libraries and runtime dependencies"]
C --> D["Operating system"]
D --> E["Hardware and virtualization resources"]
A --> F["Application configuration"]
F --> G["Environment variables"]
F --> H["Configuration files"]
A --> I["External services"]
I --> J["Database"]
I --> K["Cache and message queue"]
I --> L["Third-party API"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style L fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
VI. Development, Testing, and Production Environments
Software projects usually do not use only one runtime environment; instead, they divide multiple environments according to the software development and delivery process.
1. Development Environment (Development)
The development environment is mainly used for daily coding and debugging.
Typical characteristics:
- Allows frequent code changes.
- Uses a local database or development database.
- Enables detailed logging.
- Supports debugging tools.
- Hot reload may be enabled.
- Configuration is usually more permissive.
For example:
APP_ENV=development
DEBUG=true
LOG_LEVEL=debug
The focus of the development environment is improving development efficiency.
2. Testing Environment (Testing)
The testing environment is used to verify program behavior and quality.
Common types:
- Unit test environment.
- Integration test environment.
- Automated testing environment.
- Performance testing environment.
- Acceptance testing environment.
Typical configuration:
APP_ENV=test
DEBUG=false
LOG_LEVEL=info
The testing environment should be as close to production as possible, but it usually uses separate test data and external services.
3. Staging Environment (Staging)
The staging environment is used to simulate production and verify the deployment process and system behavior before release.
The following configurations are usually kept as consistent with production as possible:
- Operating system.
- Runtime version.
- Deployment method.
- Network structure.
- Service dependencies.
- Application configuration structure.
The staging environment does not necessarily have exactly the same resource scale as production, but key environmental differences should be minimized as much as possible.
4. Production Environment (Production)
The production environment is the runtime environment that actually handles user requests.
Main focus:
- System stability.
- Security.
- Performance.
- Availability.
- Monitoring and alerting.
- Logging and auditing.
- Data backup.
- Failure recovery.
Typical configuration:
APP_ENV=production
DEBUG=false
LOG_LEVEL=warn
The production environment should avoid outputting sensitive information and restrict debugging interfaces and unnecessary administrative permissions.
5. Comparison of Configurations Across Environments
| Comparison dimension | Development environment | Test environment | Staging environment | Production environment |
|---|---|---|---|---|
| Main purpose | Coding and debugging | Functionality verification | Pre-release validation | Provide external services |
| Log level | debug | info/debug | info | info/warn |
| Debug features | Usually enabled | Enabled on demand | Usually disabled | Disabled |
| Data | Development data | Test data | Masked or simulated data | Real business data |
| External services | Local or development services | Test services | Staging services | Production services |
| Security requirements | Basic | Relatively high | High | Highest |
6. Multi-Environment Configuration Switching Process
flowchart TD
A["Application startup"] --> B["Read APP_ENV"]
B --> C{"Identify runtime environment"}
C -->|"development"| D["Load development configuration"]
C -->|"test"| E["Load test configuration"]
C -->|"staging"| F["Load staging configuration"]
C -->|"production"| G["Load production configuration"]
C -->|"unknown"| H["Use a safe default policy or fail startup"]
D --> I["Merge configuration"]
E --> I
F --> I
G --> I
I --> J["Validate required configuration"]
J --> K{"Is the configuration valid?"}
K -->|"Yes"| L["Initialize application"]
K -->|"No"| M["Output configuration error and terminate startup"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#FFF5DE,stroke:#E8D29A,color:#334155
style L fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style M fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
7. Relationship Between Configuration Files and Environment Variables
Environment variables are not the only source of application configuration.
In real projects, configuration files, command-line arguments, configuration centers, and secret management services are also commonly used.
1. Common Configuration Sources
| Configuration source | Example | Use case |
|---|---|---|
| Default configuration | Built-in default values in the program | Basic parameters |
| Configuration file | application.yml |
Structured configuration |
| Environment variables | DATABASE_HOST |
Injected by deployment environment |
| Command-line arguments | --port=8080 |
Temporary override |
| Configuration center | Nacos, Consul, etc. | Dynamic centralized management |
| Secret management service | Vault, cloud Secret services | Sensitive configuration |
Different configuration sources have their own characteristics.
Environment variables are suitable for injecting simple configuration at deployment time, but when there is a large number of configurations, dynamic updates are required, or complex permission management is needed, it is usually necessary to combine them with a configuration center or a dedicated secret management service.
2. Configuration Priority
An application can define the priority of multiple configuration sources.
For example:
Command-line arguments
>
Environment variables
>
External configuration file
>
Default configuration
This priority ordering is a common design, but not all frameworks use exactly the same rules.
Take Spring Boot as an example: it has its own externalized configuration mechanism and defines a fairly complete priority order for property sources.
3. Configuration Loading Process
flowchart TD
A["Application startup"] --> B["Load default configuration"]
B --> C["Read configuration files"]
C --> D["Read environment variables"]
D --> E["Parse command-line arguments"]
E --> F["Merge configuration sources"]
F --> G["Perform type conversion"]
G --> H["Perform configuration validation"]
H --> I{"Is configuration valid?"}
I -->|"Yes"| J["Generate final configuration object"]
I -->|"No"| K["Report configuration error"]
J --> L["Initialize business modules"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4. Configuration Type Conversion
Environment variables are usually provided as strings, but the application needs to use different data types.
For example:
PORT=8080
DEBUG=false
TIMEOUT=30
The application needs to convert them to:
PORT → Integer
DEBUG → Boolean
TIMEOUT → Integer
Note that you cannot simply apply the default type conversion rules of every language to boolean values.
For example, in Python:
bool("false")
The result is True, because a non-empty string is treated as a truthy value.
Therefore, it should be parsed explicitly:
def parse_bool(value: str) -> bool:
normalized = value.strip().lower()
if normalized in ("true", "1", "yes", "on"):
return True
if normalized in ("false", "0", "no", "off"):
return False
raise ValueError(
f"Invalid boolean value: {value}"
)
5. Configuration Validation
After configuration is read, you cannot simply assume that all values are correct.
For example:
import os
port = int(os.getenv("PORT", "8000"))
if not 1 <= port <= 65535:
raise ValueError("Invalid port")
Real projects should also validate:
- Whether required variables exist.
- Whether data types are valid.
- Whether numeric values are within a valid range.
- Whether the URL format is correct.
- Whether file paths exist.
- Whether database connection parameters are complete.
- Whether sensitive configuration meets security requirements.
VIII. Environment Variables and Docker Containers
Container technology makes application runtime environments more standardized, but containers do not mean that environment variables are automatically shared or synchronized.
Docker can inject environment variables when creating a container.
1. Setting Environment Variables in a Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV APP_ENV=production
ENV PORT=8000
CMD ["python", "app.py"]
The ENV instruction is used to set environment variables in the image.
After the container starts, processes inside the container can read these variables.
Note: Sensitive information such as database passwords and API tokens should not be written directly into the Dockerfile, because these values may remain in the image metadata or build history.
2. Injecting environment variables with docker run
docker run \
-e APP_ENV=production \
-e PORT=8000 \
my-app
You can also use an environment variable file:
docker run \
--env-file .env \
my-app
Example .env:
APP_ENV=production
PORT=8000
LOG_LEVEL=info
An .env file is usually a configuration file by convention for applications or container tools; it is not an environment variable file that the operating system automatically recognizes.