Today, we’re diving into Docker—a powerful tool that lets you package applications into images and run them in isolated environments called containers.
At the heart of this process is the Dockerfile—a simple yet powerful file that contains all the instructions Docker needs to build your application image.
✅ What is a Docker Image?
A Docker image is like a complete snapshot of your application. It includes:
- Your app’s source code
- Required libraries and dependencies
- System tools and configurations
You can think of it like a blueprint for your app. And when you run this image, Docker creates a container—a lightweight, standalone environment for your app to run in, safely and consistently.
✅ What is a Dockerfile?
A Dockerfile is a plain text file filled with step-by-step instructions telling Docker how to build your image.
It defines things like:
- Which base image to start from (e.g. Python, Node.js)
- Which files to copy into the image
- What commands to run
- Which port the app should expose
Each instruction adds a new layer to the image, making it customizable and efficient.
✅ Why Use a Dockerfile?
Using a Dockerfile to:
- Automate the setup of environments
- Avoid "it works on my machine" issues
- Ensure consistent builds across development, testing, and production
Task Overview
You're required to:
- Create a Dockerfile for a basic web application.
- Build a Docker image from it.
- Run a container using the image.
- Test it in your browser.
- Push it to Docker Hub.
Lets use Python with Flask to build a very simple app.
Step 1: Create a Simple Web App (Python Flask)
First, create a project directory:
mkdir docker-flask-app
cd docker-flask-app
Create a file named app.py
:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello from Docker Flask app!"
Create a file named requirements.txt
:
flask
Step 2: Create a Dockerfile
Create a file named Dockerfile
(no extension):
# Use the official Python base image
FROM python:3.9-slim
# Set working directory
WORKDIR /app
# Copy app and install dependencies
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
# Copy the source code
COPY . .
# Expose port and run the app
EXPOSE 5000
CMD ["python", "app.py"]
Step 3: Build the Docker Image
In the project directory, run:
docker build -t flask-docker-app .
Step 4: Run the Docker Container
docker run -d -p 5000:5000 flask-docker-app
Now, go to your browser and open:
http://localhost:5000
You should see:
“Hello from Docker Flask app!”
Step 5: Push Image to Docker Hub
1. Tag the image
docker tag flask-docker-app your_dockerhub_username/flask-docker-app
2. Login to Docker Hub
docker login
3. Push the image
bash
docker push your_dockerhub_username/flask-docker-app
Top comments (0)