WhoBuilt

Using Docker with Next.js

Apr 2, 2021· 8 min· 45K views·Watch on YouTube

Lee Robinson, a developer at Vercel, explains how to package a Next.js app with Docker and deploy it to Google Cloud Run.

What Docker containers do

Docker packages an application, its code, and its dependencies into a container so it can run consistently across environments. Robinson briefly compares containers to cargo on a ship and notes that Kubernetes can orchestrate Docker containers.

Build a Next.js image

The Dockerfile uses three Alpine-based stages: install dependencies, build the app, and assemble a production image that starts with `yarn start`. A `.dockerignore` file excludes files that do not need to go into the container.

Build and run locally

Robinson builds the image with `docker build` and the tag `nextjs-docker-youtube`. The first build takes about 41 seconds, while a repeat build with no changes takes about 0.5 seconds because Docker reuses cached steps. He runs the app on port 3000, passing `PORT=3000` as an environment variable.

Deploy to Google Cloud Run

For deployment, Robinson installs the Google Cloud SDK, creates or selects a project, signs in with `gcloud auth login`, and enables billing. He uses Cloud Build to create the image, then deploys it to Cloud Run in `us-central1`, allows the requested permissions, and gets a URL for the running Next.js app.

Takeaways

  • Use multi-stage Docker builds to keep the production image focused and reuse cached build steps.
  • Add a `.dockerignore` file to keep unnecessary files out of the container.
  • Pass the port through an environment variable so the app can use the port expected by its deployment environment.
  • Cloud Run deployment requires a Google Cloud project with billing enabled and the image built in Cloud Build.

Mentioned in this talk

Search inside this talk

What was claimed 7

Related talks

Using Docker with Next.js · WhoBuilt