Getting Started with Docker and Next.js
Table of Contents
Introduction
This blog demonstrates a quick start guide for trying Docker with Next.js.
Requirements
Before we get started, you'll need to download Docker and Node.js so that we can run docker, npm, or node from the local environment.
Create Next.js App
Here, we'll follow the Next.js documentation to create a default Next.js web app. First, let's run the command below based on the instructions.
npx create-next-app@latest
Follow the command's instructions and it should create a Next.js app. Type http://localhost:3000 in your browser, and you'll see the default Next.js website.
Create Dockerfile
Create a file called Dockerfile and add the following content. This will use the Alpine Docker image, copy all the current directory content, run yarn install and yarn run build, and expose port 3000.
FROM node:16-alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . .
RUN yarn install
RUN yarn run build
EXPOSE 3000
CMD ["yarn", "run", "start"]
Build and Run Docker
Run the command below in the same directory. This will create a Docker image.
docker build -t my-first-docker-app .
Run this command to check the image we just created.
docker images
Now, run this command to execute the Docker image in a new container with port 9000. The -p flag is for --publish, which publishes the container's port to the host.
docker run -p 9000:3000 {the image id}
Test
You can either type http://localhost:9000 in your browser or run the command below to verify that Next.js is up and running.
curl http://localhost:9000
Conclusion
The above is a simple set of steps to create a Next.js app with Docker. Hopefully you found this blog helpful, and feel free to reach out if you want to see more content like this.