How do I build my own Docker image?

QuestionsQuestions4 SkillsProYour First Docker LabSep, 16 2025
0163

To build your own Docker image, follow these steps:

  1. Create a Directory: Start by creating a new directory for your project.

    mkdir my-app
    cd my-app
    
  2. Create a Dockerfile: In this directory, create a file named Dockerfile with the necessary instructions. Here’s a simple example:

    # Use a base image
    FROM python:3.7-slim
    
    # Set the working directory
    WORKDIR /app
    
    # Copy the current directory contents into the container
    COPY . /app
    
    # Install required packages
    RUN pip install --no-cache-dir -r requirements.txt
    
    # Set environment variables
    ENV PORT=80
    
    # Expose the port
    EXPOSE 80
    
    # Command to run the application
    CMD ["python", "app.py"]
    
  3. Create Required Files: Create a requirements.txt file for dependencies and an app.py file for your application logic. For example:

    • requirements.txt:
      flask
      
    • app.py:
      from flask import Flask
      import os
      
      app = Flask(__name__)
      
      @app.route("/")
      def hello():
          return "Hello, World!"
      
      if __name__ == "__main__":
          app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 80)))
      
  4. Build the Docker Image: Run the following command in the terminal to build your Docker image:

    docker build -t my-app .
    
  5. Run the Docker Container: After building the image, you can run it with:

    docker run -p 8888:80 my-app
    

This will start your application, and you can access it at http://localhost:8888.

Feel free to explore more about Docker and its features through LabEx labs!

0 Comments

no data
Be the first to share your comment!