Dockerize your next.js app in 2 minutes.

Dockerize your next.js app in 2 minutes.

ยท

3 min read

In this example, we are going to Dockerize a next.js application.

Docker is a great tool and it has made our lives easier as a developer. It allows us to start all kinds of projects with just a few commands without dealing with the tedious installation process and project setup process. Well, let's have a look further.

Dockerfile

A Dockerfile is a text document that contains all the commands a user could call to build and run an image.

Create a file name Dockerfile in the root directory of your project and paste the following lines.

Here is an example of a Dockerfile

# we will use the latest nodejs image as our base image
FROM node:18-alpine

# set the working directory
WORKDIR /app

# copy the package.json file
COPY package.json .

# install dependencies
RUN npm install

# copy the project in the working derectory
COPY . .

# expose the port on which our next.js application will run
EXPOSE 3000

# run the next.js application
CMD [ "npm", "run", "dev" ]

Building the docker image

Docker is very useful it can build images automatically by reading the instructions from a Dockerfile.

You can build a Docker image of your project by running the following command:

docker build -t  <image_name>

It will create a Docker image with the name you specified.

To check if the image is created or not, run the following command

docker images

it will list the images you can check for the image with the name <image_name> that you passed

Running our next.js application

Containers are running environments that contain all of the necessary elements to run your project in any environment. In this way, containers virtualize the operating system and run anywhere, irrespective of your environment.

let's run the container from the image that we have just created. To run the next.js app in a container, use the following command:

# run the container on port 3000
docker run -p 3000:3000 <image_name>

It will run the Docker image of your next.js application and map the container's port: 3000 to the host's port: 3000.

Now you can access your application at:

http://localhost:3000

Conclusion

we can run as many containers as we might need for our application. This is a very powerful feature provided by Docker because it's great for situations when we want to run an application that can be run independently on any device with just a few commands.

I hope this post will be helpful if you are looking to dockerizing your app. if it does then posting an emoji on the post would make me happy ๐Ÿ˜„.

Thanks for reading

ย