Containers · Chapter 3 of 4 · 3 min

Build and Run the Image Locally

Build the production image on your own machine, run it with your local settings, look inside it, and catch problems before the pipeline does.

Why bother locally

The pipeline builds the image for you on every merge. But when something about the container is wrong (a file missing from the image, a port mix-up, a font that is not installed), finding out from a failed deploy is slow. Building locally takes a minute and shows you exactly what production will run.

Build

From the repository folder:

docker build -t iamravi-site:local .

Run the same command twice. The second build should take seconds: every layer comes from the cache. Now change one Markdown file and build again. Only the final COPY layer and anything after it are rebuilt; the dependency install is reused. That is the layer-order trick from the previous chapter, visible in the output as CACHED lines.

Run

docker run --rm -p 8080:8080 --env-file .env iamravi-site:local

Open http://localhost:8080. This is the production image, running with your settings.

Look inside

To see what actually ended up in the image:

docker run --rm -it iamravi-site:local sh

This starts a shell in a fresh container instead of the server. Useful checks:

whoami            # should print: node
ls -la            # is .env here? it must not be
du -sh node_modules

If whoami prints root, the USER line is missing. If .env is listed, .dockerignore is missing a line, and that is a secret inside an image.

Size and history

docker image ls iamravi-site
docker history iamravi-site:local

docker history lists every layer with its size. A layer that is unexpectedly large usually means a cache, a download or a folder that should have been ignored.

Common errors and what they mean

Symptom Likely cause
npm ci fails during build package.json and package-lock.json disagree; run npm install locally and commit the lock file
Container exits at once The server crashed on start; run without -d and read the first error, often a missing environment variable
Page loads locally but not in the container The app listens on a fixed port or on 127.0.0.1 instead of 0.0.0.0
Text missing from generated images Fonts not installed in the image
Works in the container, fails on Cloud Run A setting present in your .env but not set on the service

Clean up

Images pile up. Every so often:

docker image prune

removes untagged leftovers from old builds.

Try it yourself

Build your image twice, change one content file, build a third time, and read the output. If the dependency install runs again on the third build, your Dockerfile copies code before dependencies, and every deploy is slower than it needs to be.