OneBite.Dev - Coding blog in a bite size

create a docker file

Simple docker step by step how to create a docker file with explanation

Dockerfile is a blueprint for building Docker images that contain your applications. This article will guide you, step by step, on how to create a Dockerfile.

Introduction

Docker is a widely used tool that simplifies container management. Containers allow you to run your applications in isolation, with their own resources and environment. A Dockerfile is a text document containing all the commands a user could execute on the command line to create an image.

Step 1: Start Your Dockerfile

To start your Dockerfile, open your text editor and create a new file. Name it “Dockerfile” (without an extension) and save it in the root directory of your project.

Step 2: Set the Base Image

At the start of your Dockerfile, you should define the base image for your Docker container. For instance, if your application is a Node.js app, the base image might be something like node:12.18.1. Here is how you would set that:

FROM node:12.18.1

The FROM keyword tells Docker what the source of your image will be.

Step 3: Copy your application’s source code to the Docker image

The next step is to add your application’s source code to the Docker image. The COPY command is used for this purpose. The basic syntax is as follows:

COPY . /app

This command tells Docker to copy the current directory (.) into the /app directory in the image.

Step 4: Define the Working Directory

The WORKDIR instruction sets the working directory for the Docker image, for any instructions that follow in the Dockerfile. Here is how you can set it:

WORKDIR /app

This command sets the working directory to /app. Any command that follows in the Dockerfile will be run within this directory.

Step 5: Install Dependencies

If your application requires any dependencies, this is the stage where you install them. For a Node.js application, you might use the RUN command as:

RUN npm install

Step 6: Expose necessary ports

To allow your application to be accessed from outside, you need to expose the necessary ports. You do this with the EXPOSE command:

EXPOSE 8080

This tells Docker that your application will be served on port 8080.

Step 7: Define the Command to Run Your App

Finally, you’ll need to define what command to run your application. You can do this with the CMD command. Here’s an example:

CMD [ "npm", "start" ]

This command tells Docker to start your application by running the npm start command.

Conclusion

Writing Dockerfiles is simple, but plays a crucial role in containerising your applications. Just ensure you start by selecting the correct base image and follow up by setting up your application directory and dependencies correctly. With an efficient Dockerfile, you can seamlessly create and manage Docker images for your applications.

docker