Building and Deploying a Docker Image and Container

20/12/2023 |
Loading...

This guide walks you through containerizing an application using Docker. You'll write a Dockerfile, build the image, run it as a container, and optionally push it to Docker Hub.


Step 1: Create a Dockerfile

In the root of your project, create a file named (no extension).Dockerfile

Example (Python Flask app):

# Base image FROM python:3.10-slim  # Set working directory WORKDIR /app  # Copy all project files COPY . .  # Install dependencies RUN pip install --no-cache-dir -r requirements.txt  # Expose the app port EXPOSE 5000  # Command to run the app CMD ["python", "app.py"] 

For other languages like Node.js or Java, adjust the base image and commands.


Step 2: Build the Docker Image

Open your terminal, navigate to your project directory, and run:

docker build -t my-app-image . 
  • -t my-app-image: Tags the image for easy reference.

  • .: Refers to the current directory containing the Dockerfile.


Step 3: Run the Docker Container

docker run -d -p 5000:5000 --name my-app-container my-app-image 
  • -d: Run in detached mode (in the background).

  • -p 5000:5000: Maps host port to container port.

  • --name: Gives the container a custom name.


Step 4: Check the Container

To verify it’s running:

docker ps 

Access your app by visiting:

http://localhost:5000 

(Optional) Step 5: Stop and Remove

Stop the container:

docker stop my-app-container 

Remove the container:

docker rm my-app-container 

Delete the image:

docker rmi my-app-image 

(Optional) Step 6: Push to Docker Hub

  1. Login to Docker:

    docker login 
  2. Tag the image:

    docker tag my-app-image yourusername/my-app-image 
  3. Push the image:

    docker push yourusername/my-app-image 

You can now pull this image anywhere with:

docker pull yourusername/my-app-image 

Conclusion

Using Docker, you’ve packaged your application into a lightweight, portable container that runs consistently across environments. Whether you’re deploying locally, to staging, or to production, Docker ensures your app behaves the same everywhere. This approach simplifies development, testing, and deployment—making your workflows faster and more reliable.

Get Exclusive Offers & Promotions!

Stay updated with the latest deals, discounts, and special promotions.