skip to Main Content

I Am trying to set up the debug environment for Pycharm and Python(Fastapi) in Docker (with docker-compose).
But I stuck into the problem that I cannot launch both: the debug server and the docker image.

My setup of the entry point of the app:

# import debugpy
# debugpy.listen(('0.0.0.0', 5678))
# debugpy.wait_for_client()
# print("Debugger is attached!")

import pydevd_pycharm
pydevd_pycharm.settrace('localhost', port=5678, stdoutToServer=True, stderrToServer=True)

In the Pycharm I set up port 5678 for "Python Debug Server".
So,
if I start debug in Pycharm first, then I get error during docker-compose up:
"Error response from daemon: Ports are not available: exposing port TCP 0.0.0.0:5678 -> 0.0.0.0:0: listen tcp 0.0.0.0:5678: bind: address already in use"

If I start docker-compose first, then I get the error in Pycharm while starting debug:
"Address already in use"

It looks they both want to listen for the same port on my local machine and who listens the first, gets all access.

I tried to google but nothing.

At the same time, working with VSC does have any problems. It connects to the docker container and debugs as intended.

Please advise.

2

Answers


  1. You can change the port use by your docker images. You can do this with docker-compose. You can refer to this post to understand how to do this Changing port in docker-compose.yml. Or when lanching your images with ‘run’

    Login or Signup to reply.
  2. Well, i’m sure that must be obvious by now, but you can’t really run two services on the same port of your computer at the same time, so you will have to do some forwarding. I will try to break it down to you:

    import pydevd_pycharm
    pydevd_pycharm.settrace('localhost', port=5678, stdoutToServer=True, stderrToServer=True)
    

    This snippet runs your debugger and listens to your machine’s port 5678, which is where PyCharm’s debug server will connect to. This port is now occupied and you can’t use it anymore.

    You will then update your docker-compose to use another free port. 5679, for example. Your docker-compose will look like this:

    ports:
      - "5679:5678"
    

    This will make it so your container’s port 5678 traffic, in this case, the traffic that comes from your debugger, is forwarded to your machine’s port 5679. This will make it so the two services are able to connect to each other even though they’re running on different ports.

    You will then be able to access your service through port 5679.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search