Day 17 Task: Docker Project for DevOps Engineers

Gopal GautamGopal Gautam
7 min read

🔹DockerFIle

In a Dockerfile, you can specify the base image, install software packages, copy files, set environment variables, configure ports, and define the commands to run when the container starts. Dockerfiles allow developers to automate the process of creating consistent and reproducible container images, which can then be deployed across different environments.

Attributes in a Dockerfile:

  • FROM: Specifies the base image for the new image.

  • ENV: Sets environment variables.

  • COPY/ADD: Copies files from the host to the container.

  • RUN: Executes commands during the image build process.

  • EXPOSE: Exposes a port for networking between the container and the host.

  • WORKDIR: Sets the working directory within the container.

  • CMD: Specifies the default command to run when the container starts.

  • ENTRYPOINT: Provides a command that always runs when the container starts.

  • LABEL: Adds metadata to the image.

  • VOLUME: Creates a mount point for external storage.

  • USER: Specifies the user that will run the commands in the container.

  • HEALTHCHECK: Defines a command to check the container's health.

  • ARG: Defines variables that users can pass during the build.

  • ONBUILD: Adds instructions that are triggered when the image is used as the base for another image.

🔹Deploying Python(Django) Application on aws(ec2)

  • Create EC2 Instance:

    • Log in to your AWS Management Console.

    • Navigate to the EC2 Dashboard.

    • Click on "Launch Instance" to create a new EC2 instance.

    • Choose an appropriate AMI (Amazon Machine Image), such as the latest Ubuntu Server.

    • Choose an instance type based on your requirements.

    • Configure the instance details, storage, tags, and security group as needed.

    • Review and launch the instance, selecting or creating an SSH key pair.

    • Configure Security Group: Here's where you can add port 8000. Click "Add Rule" and configure it as follows:

      • Type: Custom TCP Rule

      • Protocol: TCP

      • Port Range: 8000

      • Source: Anywhere (0.0.0.0/0)

  • Connect to EC2 Instance:

    • Use the SSH key pair you selected to connect to the EC2 instance:

        ssh -i /path/to/your/keypair.pem ubuntu@instance-public-ip
      

If you are using Django with Python 3, type:

sudo apt update
sudo apt install python3-pip  python3.10-venv
sudo apt install docker.io

Step 1: Install Django If you haven't already installed Django, you can do so by running the following command:

python3 -m venv env 
source env/bin/activate
pip install django

Step 2: Create a Django Project Next, create a new Django project by running the following command:

django-admin startproject myproject
cd myproject

This will create a new directory called "myproject" with the basic project structure.

  1. Open your Django project's settings.py file.

  2. Locate the ALLOWED_HOSTS setting. It should look like this:

     ALLOWED_HOSTS = []
    
  3. Change the empty list to ['*']:

     ALLOWED_HOSTS = ["*"]
    

Finally, run the development server by running the following command:

python3 manage.py migrate
python manage.py runserver 0.0.0.0:8000
  1. Access Django Project:

    • Open a web browser and enter the public IP of your EC2 instance followed by :8000 (e.g., http://instance-public-ip:8000) to access your Django project.

Create a Dockerfile: Create a file named Dockerfile in your Django project directory. Add the following content to it:

# Use the official Python image as the base image
FROM python:3.10.12-slim
RUN pip install --upgrade pip \
    && pip install Django==4.1.5
# Set environment variables for Django
ENV PYTHONUNBUFFERED=1

# Create and set the working directory
WORKDIR /app

# Copy the Django project into the container
COPY . /app/

# Expose the port your Django app runs on
EXPOSE 8000

# Run the Django development server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Build Docker Image: In the same directory as your Dockerfile, run the following command to build the Docker image:

docker build -t my-django-app .

Run Docker Container: After building the image, run a Docker container from the image:

docker run -p 8000:8000 my-django-app

This maps port 8000 from the container to port 8000 on your host machine.

Access Django Application: Open a web browser and enter http://publicip:8000 to access your Django application running inside the Docker container.

push your Docker image:

  1. Create a Docker Hub Account:

    • Go to the Docker Hub website: https://hub.docker.com/

    • Click on the "Sign Up" button.

    • Enter your desired username, email address, and password.

    • Complete the reCAPTCHA and agree to the terms of service.

    • Click the "Sign Up" button to create your account.

  2. Create a Repository:

    • Once you're logged in to your Docker Hub account, you'll see your profile dashboard.

    • Click on the "Create Repository" button.

    • Choose a name for your repository. This is where your Docker images will be stored.

    • Select whether the repository will be public or private (for private repositories, you might need a subscription).

    • You can add a description and choose other settings if needed.

    • Click the "Create" button to create the repository.

Now you have a Docker Hub account and a repository where you can push your Docker images.

After creating the repository, you can follow the steps mentioned earlier to tag and push your Docker image to the repository. Remember to replace <your-dockerhub-username> with your actual Docker Hub username and <image-name> with the name of your Docker image.

Tag Your Docker Image: Before pushing, you need to tag your local Docker image to match the repository's naming convention. The format is <repository-name>/<image-name>:<tag>.

docker tag my-django-app:latest <your-dockerhub-username>/my-django-app:latest

Login to Docker Hub: If you haven't already, log in to your Docker Hub account using the following command:

docker login

Enter your Docker Hub username and password.

Push Docker Image: Push the tagged Docker image to the repository:

docker push <your-dockerhub-username>/my-django-app:lates

Replace <your-dockerhub-username> with your actual Docker Hub username.

Access the Image on Docker Hub: Visit your Docker Hub account online and navigate to the repository. You should see your pushed Docker image listed there.

🔹Configure Nginx to Proxy Pass

Start by creating and opening a new server block in Nginx’s sites-available directory:

sudo nano /etc/nginx/sites-available/myproject
server {
        listen 80;
        server_name  public_ip;

        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
ln -s /etc/nginx/sites-available/myproject etc/nginx/sites-available/
systemctl restart nginx

Now, NGINX is acting as a reverse proxy for your Django application.Open a web browser and enter http://publicip to access your Django application.

🔹Secure your application with SSL

  1. Obtain EC2 Public IP: Log in to your AWS Management Console and navigate to the EC2 Dashboard. Find your EC2 instance and note down its public IP address.

  2. Access Domain Registrar's Control Panel: Log in to your domain registrar's control panel. This is where you originally registered your domain "Domain.com".

  3. Access DNS Settings: Look for a section in your domain registrar's control panel labeled "DNS Settings," "DNS Management," or something similar.

  4. Edit DNS Records: Find the DNS records associated with your domain. You will typically see records like A, CNAME, MX, etc.

  5. Add an A Record: Add a new A record to map your domain to the EC2 instance's public IP address:

    • Type: A

    • Name: @ (or leave it blank)

    • Value: Your EC2 instance's public IP address

    • TTL: Choose an appropriate TTL (time to live) value

  6. Save Changes: Save the changes you made to the DNS records. This might take some time to propagate across the DNS servers on the internet.

sudo nano /etc/nginx/sites-available/myproject
server {
        listen 80;
        server_name  Domain_name;

        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
sudo systemctl restart nginx
sudo ufw allow 443

Install Certbot: If you haven't already, install Certbot on your system. You can use the following command:

sudo snap install --classic certbot

Obtain SSL Certificate: Run Certbot with the --nginx plugin to automatically configure SSL for your Nginx server:

sudo certbot --nginx -d domain_name

Test Your Setup: Open a web browser and enter your domain "Domain.com". It should now direct you to your EC2 instance's web server.

0
Subscribe to my newsletter

Read articles from Gopal Gautam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gopal Gautam
Gopal Gautam

Hii I am a backend/DevOps engineer.I have a experience with development and automation.I mostly work with Python, django, Cloud based technologies.