Docker commands



This content originally appeared on DEV Community and was authored by Pranav Bakare

Here are the steps with sample Docker commands:

  1. Develop: Write your application code (e.g., a Python or Node.js application).

  2. Dockerfile: Create a file named Dockerfile in the root of your project directory. Example Dockerfile for a Python Flask app:

   # Use an official Python runtime as a parent image
   FROM python:3.9-slim

   # Set the working directory
   WORKDIR /app

   # Copy the current directory contents into the container at /app
   COPY . /app

   # Install any needed packages specified in requirements.txt
   RUN pip install --no-cache-dir -r requirements.txt

   # Make port 80 available to the world outside this container
   EXPOSE 80

   # Define environment variable
   ENV NAME World

   # Run app.py when the container launches
   CMD ["python", "app.py"]
  1. Build Image: Run this command in your terminal to build your Docker image:
   docker build -t my-app .

Here, -t my-app tags the image as my-app.

  1. Run Container: Use the following command to start a container from the image:
   docker run -d -p 5000:80 my-app

The -d flag runs the container in the background, and -p 5000:80 maps port 5000 on your machine to port 80 on the container.

  1. Test: After running the container, test the app by opening http://localhost:5000 in your browser. If you make changes to your code:

    • Rebuild the image:
     docker build -t my-app .
    
  • Stop the old container:

     docker stop <container_id>
    
  • Remove the container:

     docker rm <container_id>
    
  • Run a new container with the updated image:

     docker run -d -p 5000:80 my-app
    
  1. Push (Optional): To share your Docker image on Docker Hub, first log in to Docker Hub:
   docker login

Then push your image:

   docker tag my-app your_dockerhub_username/my-app
   docker push your_dockerhub_username/my-app
  1. Pull (Optional): Others can pull your image from Docker Hub and run it using:
   docker pull your_dockerhub_username/my-app
   docker run -d -p 5000:80 your_dockerhub_username/my-app

These commands will help you get started with containerizing and sharing your application using Docker. Let me know if you need further assistance!


This content originally appeared on DEV Community and was authored by Pranav Bakare