Get Start with Docker with Next.js

2022/03/182 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Requirements
  3. Create Next.js App
  4. Create Dockerfile
  5. Build and Run Docker
  6. Test Result
  7. Conclusion

Introduction

This blog demo a quick start for if you want to try the docker with Next.js.

Requirements

Before, we get start, you'll need to download the Docker and Node.js, so later we can run docker or npm or node from the local environment.

  • Install the Docker
  • Install the Node.js

Create Next.js App

Here, we'll follow Next.js documentation to create a default Next.js web app, at first, let's run below command base on the instruction.

npx create-next-app@latest

Follow the command's instruction then it should create a Next.js, type http://localhost:3000 at your browser, you'll see the default Next.js website.

Create Dockerfile

Create a file Dockerfile then put below content, this will use the Alpine Docker image, then copy all current directory content, then run the yarn install and yarn run build and expose the 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 below command at the same directory, this'll 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 then will execute the docker image in a new container with port 9000. the -p is the --publish which publish the container's port to the host.

docker run -p 9000:3000 {the image id}

Test

You can either type URL http://localhost:9000 at browser, or run below to verify the Next.js is up and running.

curl http://localhost:9000

Conclusion

Above is an simple steps to create Next.js app with Docker, hopefully you like this blog and feel free to reach out if you want to see more of this kind of blogs.