ANI

Python to correct an error in Docker: Student lesson

Python to correct an error in Docker: Student lesson
Photo for Author | Ideogram

Obvious Introduction

Designer Limastic is made to grow, the ship, and run applications by providing consistent sites in different days. However, this flexibility comes with illegal trading: Adjusting is complicated to beginners when your apps – including Python apps – apply within the Docker containers.

For those new to Docker, the Python error systems can feel like trying to repair the car by hood. You know something is wrong, but you can't see what happens inside.

This first study lesson will teach you how to start with Debugging Python in Docker.

Obvious Why is the abuse in the docker different?

Before we go inside, let's understand why the docker makes it reported. When you run python in your area on your machine, you can:

  • See errone messages immediately
  • Edit files and run them again
  • Use your Debugging Tools
  • Check which files exist and what's in it

But when Python runs inside the dock dish, it is usually a tricky and straightforward, especially if you are a start. The container has its file system, its environment, and its practical procedures.

Obvious To Set Our Example

Let's start with a simple Python system with a bug. Don't worry about Docker right now; Let us first understand what we use.

Create a file called app.py:

def calculate_sum(numbers):
    total = 0
    for num in numbers:
        total += num
        print(f"Adding {num}, total is now {total}")
    return total

def main():
    numbers = [1, 2, 3, 4, 5]
    result = calculate_sum(numbers)
    print(f"Final result: {result}")
    
    # This line will cause our program to crash!
    division_result = 10 / 0
    print(f"Division result: {division_result}")

if __name__ == "__main__":
    main()

If you are using this regularly with python3 app.pyYou will see counting well but then crashes in error “Division Division by zero” zero “. It is easy to see and repair, so?

Now let's see what happens when this simple app works within the Docker dish.

Obvious To build your first docker container

We need to tell Docker how to install our Python program. Create a File called Dockerfile`:

FROM python:3.11-slim

WORKDIR /app

COPY app.py .

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

Let me explain each line:

  • FROM python:3.11-slim Tells young girlfriend to start with the Linux program made before Linux already equipped with Python
  • WORKDIR /app creates a folder of `/ App` within the container and puts it as an active indicator
  • COPY app.py . Chooping your app.py File from your computer logged on `/ app`lger within a container
  • CMD ["python3", "app.py"] Tells him dragged to the command for any instruction to work when the container begins

Now let's build and run this dish:

docker build -t my-python-app .
docker run my-python-app

You will see the output, including error, but then the container stops and comes out. This leaves you finding what went wrong inside the bowl itself.

Obvious 1. Running time to use the problem

The first ability to correct the error you need learn how to get inside the rider container and check out potential problems.

Instead of using your Python's system immediately, let's start the bowl and get a quick command within you:

docker run -it my-python-app /bin/bash

Let me get rid of these new flags:

  • -i It means “Interactive” – Keeps the Broadcasting Open In order to type in instructions
  • -t Allegiance for “pseudo-Ty” – basically, makes Terminal work well
  • /bin/bash Fill a common command and give you a bash shell instead

Now that you have a terminal within a container, you can run the instructions such as:

# See what directory you're in
pwd

# List files in the current directory
ls -la

# Look at your Python file
cat app.py

# Run your Python program
python3 app.py

You will see the error:

root@fd1d0355b9e2:/app# python3 app.py
Adding 1, total is now 1
Adding 2, total is now 3
Adding 3, total is now 6
Adding 4, total is now 10
Adding 5, total is now 15
Final result: 15
Traceback (most recent call last):
  File "/app/app.py", line 18, in 
    main()
  File "/app/app.py", line 14, in main
    division_result = 10 / 0
                      ~~~^~~
ZeroDivisionError: division by zero

You can now:

  • Edit the file here in a container (although you need to enter Editor first)
  • Check the environment to understand different
  • Explore smaller pieces of code by contacting

Adjust the separation of zero error (maybe change `10/20` in` 10/2`), save the file, and run it again.

The problem is fixed. When you get out of the container, anyway, you lose the changes track you made. This brings us to our next process.

Obvious 2. Using volume placement to find live planning

Wouldn't it be good if you could edit the files on your computer and have automatic changes appear inside the container? That is exactly what the input of the volume is done.

docker run -it -v $(pwd):/app my-python-app /bin/bash

The new part here -v $(pwd):/app:

  • $(pwd) issuing the current method of guidelines.
  • :/app Your current maps /app within a container.
  • Any file you change on your computer changes quickly within the container.

You can now:

  1. Arrange app.py On your computer using your favorite editor
  2. Within the container, run python3 app.py Exploring Your Changes
  3. Continue to organize and test until activated

Here is the sample result after changing partition to 2:

root@3790528635bc:/app# python3 app.py
Adding 1, total is now 1
Adding 2, total is now 3
Adding 3, total is now 6
Adding 4, total is now 10
Adding 5, total is now 15
Final result: 15
Division result: 5.0

This is useful because you get to use your planning environment that is familiar with your computer and the same nature within the container.

Obvious 3. Connecting a remote Debugger from EDE

If you are using a combination of improvement (right) as VS code or PycharmYou can actually connect your Idi's error directly to the code running within the Docker dish. This gives you complete energy for your Debugging Tools.

Edit `dockerie` as you:

FROM python:3.11-slim

WORKDIR /app

# Install the remote debugging library
RUN pip install debugpy

COPY app.py .

# Expose the port that the debugger will use
EXPOSE 5678

# Start the program with debugger support
CMD ["python3", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "app.py"]

What you do:

  • pip install debugpy Includes Microsoft's A deberch the library.
  • EXPOSE 5678 It tells a damsel that our bowl will use Port 5678.
  • This page CMD It launches our program with Debugger, listening to Port 5678 by communicating. No changes in your Python code required.

Build and use a container:

docker build -t my-python-app .
docker run -p 5678:5678 my-python-app

This page -p 5678:5678 Maps Port 5678 From the Port 5678 container on your computer.

Now in the VS code, you can set up Debug Configuration (in .vscode/launch.json) Connection in a container:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "connect": {
                "host": "localhost",
                "port": 5678
            }
        }
    ]
}

If you start correcting the VS code, it will connect to your container, and you can put the chips, check the variable, and log in with the code as you would like in the area code.

Obvious General Problems Preparing Solution

⚠️ “My plan works on my computer but not in Docker”

This often means there is a difference in nature. See:

  • Python Version Difference.
  • Lostness lost.
  • Different forms of file.
  • Variations of nature.
  • Permissions for file.

⚠️ “I don't see my print statements”

  • Work python -u avoiding the buffect's output.
  • Make sure you're running with -it If you want to get out the active.
  • Check that your system is active as intended (perhaps from early).

⚠️ “My Changes don't show”

  • Make sure you use volume placement (-v).
  • Check that you are planning the correct file.
  • Make sure the file is copied in the container.

⚠️ “A bowl comes out immediately”

  • Run with /bin/bash to examine the scene.
  • Check error messages with docker logs container_name.
  • Make sure you are your CMD In dockfile is correct.

Obvious Store

You now have a basic Python Tool of Dobugging Edocker:

  1. Active shells (docker run -it ... /bin/bash) Checking and quick adjustment
  2. The volume of the volume (-v $(pwd):/app) Editing your local file system
  3. Deserved Desert Through Your Full Skills

After this, you can try to use a docker designed to control complex programs. In the meantime, first in the simple ways. Many Debugging problems can only be resolved by entering inside and crying.

The key must be a way: understand what to happen, find out what happens in fact, and closes the gap between the two. Repair a fun error!

Count Priya c He is the writer and a technical writer from India. He likes to work in mathematical communication, data science and content creation. His areas of interest and professionals includes deliefs, data science and natural language. She enjoys reading, writing, coding, and coffee! Currently, he works by reading and sharing his knowledge and engineering society by disciples of teaching, how they guide, pieces of ideas, and more. Calculate and create views of the resources and instruction of codes.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button