5 steps to Deploy docker image to Kubernetes (FOR BEGINNERS UPDATED)
Table of Contents
Introduction
This tutorial will guide you through the essential steps to deploy a Docker image to Kubernetes, aimed specifically at beginners. By following these steps, you will learn how to create a Dockerfile, build a Docker image, push it to Docker Hub, and finally, deploy it in a Kubernetes cluster.
Step 1: Prepare Your Environment
Before starting, ensure you have the following prerequisites:
- Docker installed and running on your laptop.
- A free Docker Hub account created.
- Git Bash installed to run Linux commands (for Windows users).
- Minikube installed on your laptop to create a local Kubernetes cluster.
Step 2: Create a Dockerfile
-
Open Git Bash or terminal.
-
Create a new folder for your Docker project:
mkdir docker cd docker
-
Create a new file named
Dockerfile
:touch Dockerfile
-
Open the Dockerfile in a text editor (e.g., Vim):
vi Dockerfile
-
Add the following lines to the Dockerfile:
FROM nginx COPY index.html /usr/share/nginx/html/index.html
- This line extends the existing Nginx image and overrides the default
index.html
file.
- This line extends the existing Nginx image and overrides the default
-
Save and exit the editor.
Step 3: Create the index.html File
- Create an
index.html
file in the same directory:touch index.html
- Open the file in a text editor:
vi index.html
- Add your desired content to
index.html
, then save and exit.
Step 4: Build the Docker Image
-
In the terminal, build your Docker image with the following command:
docker build -t yourusername/nginx-demo:1.0 .
- Replace
yourusername
with your Docker Hub username. - The
.
indicates the current directory.
- Replace
-
After the image is built, you can verify it by running:
docker images
Step 5: Push the Docker Image to Docker Hub
- Log in to Docker Hub from the terminal:
docker login
- Push your newly created Docker image to Docker Hub:
docker push yourusername/nginx-demo:1.0
- Refresh Docker Hub to see your pushed image and its tags.
Step 6: Deploy the Docker Image in Minikube
- Start Minikube if it’s not already running:
minikube start
- Create a Kubernetes pod using the following command:
kubectl run demo-nginx --image=yourusername/nginx-demo:1.0 --port=80
- Check the status of the pod:
kubectl get pods
- Create a service to expose the pod:
kubectl expose pod demo-nginx --type=NodePort --port=80
- Forward the service to access it from your laptop:
kubectl port-forward service/demo-nginx 7080:80
Conclusion
You have successfully deployed a Docker image to Kubernetes. You learned how to create a Dockerfile, build and push a Docker image to Docker Hub, and deploy it as a pod in a local Kubernetes cluster. The next steps could involve exploring more advanced Kubernetes features or integrating your deployment into a CI/CD pipeline.