Working directory

2 snippets across 2 stacks - Docker, Python

DKDocker

WORKDIR - Set Working Directory

DK · Dockerfile
Syntax
WORKDIR /path/to/dir
Example
WORKDIR /app
COPY . .
RUN npm ci

Note All subsequent RUN, CMD, COPY, and ENTRYPOINT instructions use this directory. WORKDIR creates the directory if it does not exist. Avoid using RUN cd /app - it only affects that single RUN layer.

PYPython

os and os.path

PY · Common Standard Library
Syntax
import os
os.path.join()
os.environ
Example
import os

# Environment variables
db_host = os.environ.get("DB_HOST", "localhost")
print(f"DB: {db_host}")

# Path operations (prefer pathlib for new code)
print(os.path.expanduser("~"))
print(os.path.splitext("report.pdf"))
print(os.getcwd())
Output
DB: localhost
/Users/username
('report', '.pdf')
/current/directory

Note Prefer pathlib.Path for path manipulation in new code. os.environ provides direct access to environment variables. Use os.getenv() for safe access with defaults.

Frequently asked questions

How does Docker handle working directory?
This task is covered in 2 stacks on this page: Docker, Python. The "WORKDIR - Set Working Directory" snippet in Docker uses `WORKDIR /path/to/dir`.
Which command does the Docker example use?
The "WORKDIR - Set Working Directory" snippet uses `WORKDIR /path/to/dir`, from the Dockerfile section of the Docker cheat sheet.
Which stacks cover "working directory" on this page?
Docker, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "WORKDIR - Set Working Directory": All subsequent RUN, CMD, COPY, and ENTRYPOINT instructions use this directory. WORKDIR creates the directory if it does not exist. Avoid using RUN cd /app - it only affects that single RUN layer.