What Is a Build Context?
The build context is the set of files and folders the Docker CLI packages and sends to the Docker daemon when runningdocker build. By default, Docker uses the current directory (.) as the build context.
- Archives everything under
.. - Sends it to the Docker daemon.
- Unpacks it into a temporary directory (e.g.,
/var/lib/docker/tmp/...). - Executes the instructions in your
Dockerfile.
If you omit the
-t (tag) flag, Docker builds the image and assigns the latest tag by default:Example Dockerfile for a Flask App
Specifying a Different Build Context
You can point Docker to any local directory containing yourDockerfile:
/opt/my-custom-app/Dockerfile and include all files under /opt/my-custom-app in the context.
Common Context Sources
| Context Source | Command Example | Description |
|---|---|---|
| Current directory | docker build . -t my-custom-app | Sends . as the context |
| Local path | docker build /opt/my-custom-app -t my-custom-app | Uses a specified folder |
| Git repository | docker build https://github.com/myaccount/myapp.git#feature-branch | Clones a repo (or branch) as the build context |
| Custom Dockerfile | docker build -f Dockerfile.dev https://github.com/myaccount/myapp.git | Specifies an alternative Dockerfile location |
Managing Context Size with .dockerignore
Sending large or unnecessary files (logs, build artifacts) can slow down builds, especially when the daemon is remote. To prevent this, create a .dockerignore file in your context root:
Be careful: missing important source files in
.dockerignore can lead to build failures or incomplete images.Remote Docker Daemon Output
When using a remote Docker daemon, you’ll see output similar to:Building from a Git Repository
Docker can directly use Git URLs as the build context:Dockerfile at the root of the checked‐out code. Use -f to point to a different file:
Summary
- The build context defines what files are sent to the Docker daemon.
- Use
.dockerignoreto exclude unnecessary files and speed up builds. - You can build from local paths or Git repositories.
- The
-fflag lets you specify a non-default Dockerfile.