Git Docker Integration
In this page:
Git and Docker Overview
Packaging your application as a Docker container captures its exact runtime environment — OS, dependencies, versions — so "works on my machine" stops being a real risk, since the same image runs identically wherever it's deployed.
Example: Git and Docker Overview
docker build -t myapp .
docker run myapp
The .dockerignore File
A .dockerignore file works like .gitignore but for Docker builds — listing .git/, local env files, and node_modules-style directories here keeps them out of the build context entirely, which shrinks image size and avoids accidentally baking secrets or version-control internals into a shipped container.
Example: The .dockerignore File
echo ".git/\n.env\nnode_modules/" > .dockerignore
Tagging Images with Commit Hashes
Tagging an image with the short commit hash (docker build -t myapp:$(git rev-parse --short HEAD) .) ties every running container back to the exact source code it was built from, which makes tracking down which commit is live, or rolling back to a known-good one, straightforward.
Example: Tagging Images with Commit Hashes
docker build -t myapp:$(git rev-parse --short HEAD) .
Automating Docker Builds
Wiring docker build and docker push into your CI/CD pipeline means a fresh image gets built and published automatically whenever code merges — removing the manual, easy-to-forget step of building and pushing images by hand before every deploy.
Example: Automating Docker Builds
steps:
- run: docker build -t myapp:${{ github.sha }} .
- run: docker push myapp:${{ github.sha }}
Running Local Containers
Running a freshly built image locally (docker run) before pushing it anywhere lets you catch a broken startup, missing environment variable, or misconfigured port mapping while it's still cheap to fix, rather than after it's already failing in production.
Example: Running Local Containers
docker build -t myapp .
docker run -p 3000:3000 myapp
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: