Docker 101: A Practical Introduction for Beginners

5 min read by M1NDB3ND3R
dockercontainersdevopstutorialbeginnerflaskpython

Introduction to Docker

Basic Commands :

Docker Logo

Check version of Docker

docker version
Docker Version

Display system-wide information

docker info
Docker Info

Docker Help

docker --help
Docker Help

To login to Hub.docker.com ( Docker Registry )

docker login
Docker Login

To search a image in Registry ( hub.docker.com )

docker search <image>
Docker Search

To Pull a image from Registry ( hub.docker.com )

docker pull <images>
Docker Pull

To list all the images in our system

docker images
Docker Images

To Remove a Image

docker rmi <image_name>
Docker Remove Image

To View Running Container

Use flag : -a to view all container including stopped

docker ps
Docker PS

Pulling nginx container

docker search nginx
docker pull nginx
Docker Search and Pull

Create a container from image or run a image as container

Flag : -i -> iteractive
Flag : -d -> detached
Flag : -t -> teletypewriter (tty)
Flag : -p -> port mapping

docker run -itd <image>
docker run -itd <image> --name <container_name>
Docker Run Docker Run with Name

To Stop a running Container

docker stop <container-id>
Docker Stop Docker Stop

To Restart a Container

docker restart <container-id>
Docker Restart

To Start a Container

docker start <container-id>
Docker Start

To remove a container

docker rm <container-id>
Docker Remove Container

To View a log of container

docker logs <container-id>
Docker Logs

Port Mapping in Docker Container with system

docker run -itd -p <host-port>:<container-port> <image> 
Docker Port Mapping Docker Port Mapping Docker Port Mapping

To inspect a docker image

docker inspect <image name>
Docker Inspect

To save a image as tar file

docker save -o <tar file name> <image name>
Docker Save

To unzip or load unzipped file

docker load -i <Tar file name>
Docker Load

To execute a container

docker exec -it <Container-ID> /bin/bash
Docker Exec

To rename a Container

docker rename <old_name> <new_name>
Docker Rename

To view history of image

docker history <image name>
Docker History

System prune ( remove everything )

docker system prune
Docker System Prune

logout from hub.docker.com

docker logout
Docker Logout

Working with python and flask

Simple Program to learn routing

Create a env and install dependencies

python3 -m venv .env
source .env/bin/activate

.\.env\Script\activate // For windows
pip install -U pip
pip install flask

app.py

from flask import Flask

app = Flask(__name__)


@app.route("/")
def main():
    return "Student Detail"


@app.route("/getdetail")
def get_detail():
    return "7376221CS334 - THARUN D V"


if __name__ == "__main__":
    app.run(debug=True)
Docker Python Environment

To run flask application

python3 app.py
Docker Flask Application Docker Flask Application Docker Flask Application Docker Flask Application Docker Flask Application

learning to write docker file and converting above simple flask code to docker images and creating a container

Basics of Dockerfile

Dockerfile

Writing a Docker file for above flask app

FROM python:3.9-alpine
MAINTAINER "THARUN-DV"
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5000
ENV FLASK_APP=app.py
CMD ["flask" , "run", "--host","0.0.0.0"]
Dockerfile

Building the Dockerfile

docker build -t <image_name> <path to Dockerfile>
Docker Build Docker Build

Create a container using the above image

docker run -itd -p 80:5000 <image_name>
Docker Run Docker Run Docker Run

Pushing the image to registry ( hub.docker.com )

docker push <image_name>
Docker Push Docker Push

Testing Other docker images :

Pulling a Docker images

docker pull m1ndb3nd3r/flask-hello
Docker Pull

create a container exposing host post 80 and container 3000

  • since I use arm based machine cannot pull and run x86 or x64 based images so pulled my own image and executed
docker run -itd -p 80:5000 m1ndb3nd3r/flask-hello
Docker Run Docker Run Docker Run
  • Flask application executed successfully

Docker Compose

[[https://www.programonaut.com/wp-content/uploads/2021/07/docker-compose-cheat-sheet.pdf]] Docker Compose Docker Compose

Check docker compose version

docker compose version
Docker Compose Version

Creating a docker compose file

version: "3"
services:
  nginx:
    image: "nginx:latest"
    container_name: nginx_container
    restart: always
    ports:
      - "7777:80"
  httpd:
    image: "httpd:latest"
    container_name: httpd_container
    restart: always
    ports:
      - "8888:80"
Docker Compose File

Create and start containers

docker compose up

use flag -d to run in background

Docker Compose Up

To list compose containers

docker compose ps
Docker Compose PS

To stop compose containers

docker compose stop 
Docker Compose Stop

docker compose log

docker compose logs
Docker Compose Logs

Docker compose restart

Docker Compose Restart

Stop and remove containers, networks

docker compose down
Docker Compose Down

Dockerize a simple application

Sample Ml app. (iris data classification using random forest classification algorithm )

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import joblib

# Load dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# Create a Gaussian Classifier
clf = RandomForestClassifier()

# Train the model using the training sets
clf.fit(X_train, y_train)

# Predict the response for test dataset
y_pred = clf.predict(X_test)

# Model Accuracy, how often is the classifier correct?
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")

# Save the trained model
joblib.dump(clf, 'iris_model.pkl')
print("Model saved!")
Docker ML App

Creating a dockerfile for it

FROM python:3.9-slim
MAINTAINER "THARUN D V"
WORKDIR /app 
COPY . /app 
RUN pip install --no-cache-dir -r requirements.txt

CMD ["python3","app.py"]
Dockerfile

Build docker file

docker build -t <image_name> <path_to_dockerfile>
Docker Build

login to docker registery

docker login
Docker Login

Push docker image to hub.docker.com

docker push <image_name>
Docker Push

create a container using the builded image

docker run -itd <imagename>
Docker Run

view output using logs

docker logs <container-id>
Docker Logs