Dockerfile Basics

Dockerfile Basics

A Dockerfile is a script containing a set of instructions to automate the creation of Docker images. It defines everything needed to run an application, including:
✔ Base Image – The starting point (e.g., Ubuntu, Python, Node.js).
✔ Dependencies – Libraries and packages required by the app.
✔ Configurations – Environment variables, file paths, ports, etc.
✔ Execution Commands – How the application should start.

Why Use a Dockerfile?

✅ Automates the image creation process.
✅ Ensures consistency across different environments.
✅ Makes application deployment easier and faster.

Basic Structure of a Dockerfile

A simple Dockerfile looks like this:

# 1️. Specify the base image 

FROM python:3.9 

 

# 2️. Set the working directory 

WORKDIR /app 

 

# 3️.Copy application files 

COPY . /app 

 

# 4️. Install dependencies 

RUN pip install -r requirements.txt 

 

# 5️. Expose a port (optional) 

EXPOSE 5000 

 

# 6️. Define the command to run the app 

CMD [“python”, “app.py”]

Understanding Dockerfile Instructions

1️. FROM – Specify the Base Image

Defines the starting point for your application.
Example:

FROM ubuntu:latest

or

FROM node:16

2️. WORKDIR – Set the Working Directory

Defines the folder where commands will run inside the container.

WORKDIR /app

3️. COPY – Copy Files into the Container

Copies application files from the host to the container.

COPY . /app

4️. RUN – Execute Commands Inside the Image

Used to install dependencies or configure the system.

RUN apt-get update && apt-get install -y curl

or

RUN pip install -r requirements.txt

5️. EXPOSE – Define the Application Port

Opens a port for communication.

Dockerfile


EXPOSE 8080

6️. CMD – Define the Default Command

Specifies what the container should do when it starts.

CMD [“node”, “server.js”]

or

CMD [“python”, “app.py”]

Building and Running an Image from a Dockerfile

1️. Build the Image

Run the following command in the folder where the Dockerfile is saved:

docker build -t my_app .

2️. Run a Container from the Image

docker run -d -p 5000:5000 my_app

Now your application is running inside a container!

Conclusion

  A Dockerfile is a script that automates the creation of Docker images.
•  It defines dependencies, configurations, and execution commands.
•  Using docker build and docker run, you can create and deploy containers easily.

Chatbot