如何将 PyCharm 连接到位于 Docker 容器内的 python 解释器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27343452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect PyCharm to a python interpreter located inside a Docker container?
提问by trikoder_beta
I'm starting with Docker, but I don't know how to configure PyCharm to use a python interpreter located in a container.
我从 Docker 开始,但我不知道如何配置 PyCharm 以使用位于容器中的 python 解释器。
It was easy to setup with Vagrant, but there's apparently no official way to do it with Dockeryet.
使用 Vagrant 进行设置很容易,但显然还没有官方的方法可以使用 Docker 进行设置。
Should I prepare special Docker image with exposed ssh port? How to do that more easily?
我应该使用暴露的 ssh 端口准备特殊的 Docker 镜像吗?如何更轻松地做到这一点?
回答by dukebody
With Docker 1.3, use the exec
command to construct the path to the Python interpreter:
对于 Docker 1.3,使用以下exec
命令构建 Python 解释器的路径:
sudo docker exec container_name /usr/bin/python
See https://docs.docker.com/reference/commandline/cli/#exec, http://forum.jetbrains.com/thread/PyCharm-2224
见https://docs.docker.com/reference/commandline/cli/#exec,http://forum.jetbrains.com/thread/PyCharm-2224
You could install SSH inside the container and then expose the port, but that isn't how containers are expected to be used, because you would be bloating them.
您可以在容器内安装 SSH,然后公开端口,但这不是容器的预期使用方式,因为您会使它们膨胀。
回答by Anto
In order to avoid any SSH overhead (which makes perfect sense with Docker), docker exec
definitely seems to be the way to go.
Unfortunately I couldn't get it to work so far. It would be great if someone could fill in the blanks. Here is what I did (using PyCharm 4.0.4 and Docker 1.4.1):
为了避免任何 SSH 开销(这对 Docker 来说非常有意义),docker exec
绝对是要走的路。
不幸的是,到目前为止我无法让它工作。如果有人可以填补空白,那就太好了。这是我所做的(使用 PyCharm 4.0.4 和 Docker 1.4.1):
Create a file named
python_myproject.sh
containing the following:#!/bin/bash docker exec -i myproject_container /path/to/containers/python2.7
Note that the file's name has to begin with
python
otherwise PyCharm will complain.In PyCharm's settings, under
Project Interpreter
, add a new local interpreter. Give it the path to yourpython_myproject.sh
file.
创建一个名为
python_myproject.sh
包含以下内容的文件:#!/bin/bash docker exec -i myproject_container /path/to/containers/python2.7
请注意,文件名必须以 开头,
python
否则 PyCharm 会报错。在 PyCharm 的设置下
Project Interpreter
,添加一个新的本地解释器。给它你的python_myproject.sh
文件的路径。
This is where I'm stuck. After a quite long loading time (the throbber says "Setting up library files"), a window entitled "Invalid Python SDK" appears and says:
这就是我被困的地方。经过相当长的加载时间后(throbber 说“设置库文件”),会出现一个标题为“无效的 Python SDK”的窗口并显示:
Cannot set up a python SDK
at /path/to/python_myproject.sh.
The SDK seems invalid.
无法
在 /path/to/python_myproject.sh设置 python SDK 。
SDK 似乎无效。
In ~/.PyCharm40/system/log/.idea
:
在~/.PyCharm40/system/log/.idea
:
2015-02-19 17:33:30,569 [ 166966] WARN - ution.process.OSProcessHandler - Cannot kill process tree. Trying to destroy process using Java API. Cmdline:
2015-02-19 17:34:30,628 [ 227025] WARN - ution.process.OSProcessHandler - Cannot kill process tree. Trying to destroy process using Java API. Cmdline:
2015-02-19 17:34:30,653 [ 227050] INFO - rains.python.sdk.PythonSdkType -
Timed out
回答by taleinat
I haven't tried this, but I would try creating a Bash script which calls docker exec ...
, as in @Anto's answer.
我还没有尝试过这个,但我会尝试创建一个调用 的 Bash 脚本docker exec ...
,就像@Anto 的回答一样。
Then, install the BashSupport extension. Now create a new run configurationwhich runs your script as a Bash script.
然后,安装BashSupport 扩展。现在创建一个新的运行配置,它将您的脚本作为 Bash 脚本运行。
回答by grim
You can get a bit crazy by installing Pycharm in the container and just running it from there. You'd have to do this by docker run -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=:0.0 pycharm-image
but it should work just fine. But remember that all of Pycharm and your source would be in that container as well. So save, commit, and push early and often.
通过在容器中安装 Pycharm 并从那里运行它,您可能会有点疯狂。你必须这样做,docker run -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=:0.0 pycharm-image
但它应该可以正常工作。但请记住,所有 Pycharm 和您的源代码也将在该容器中。因此,尽早并经常保存、提交和推送。
回答by m1keil
I don't think it's so bad to include SSH inside your container if you really need it. Yes, it's not essential in other use cases since the introduction of docker exec
but since Intellij/PyCharm only support remote interpreter via SSH, it's OK.
如果你真的需要它,我认为在你的容器中包含 SSH 并没有那么糟糕。是的,自引入以来它在其他用例中不是必需的,docker exec
但由于 Intellij/PyCharm 仅支持通过 SSH 的远程解释器,所以没关系。
You can use phusion/baseimage
as a good starting point to build your own container with SSH and any version of Python you need (it comes by default with PY3).
您可以将其phusion/baseimage
用作使用 SSH 和您需要的任何 Python 版本(默认情况下随 PY3 一起提供)构建您自己的容器的良好起点。
Theoretically, it would be ideal to keep using Vagrant for this task as well, since it allows you to create a workflow that will work both on Windows/OS X machines (by using boot2docker) and Linux (native Docker).
从理论上讲,继续使用 Vagrant 来完成这项任务也是理想的,因为它允许您创建一个工作流,可以在 Windows/OS X 机器(通过使用 boot2docker)和 Linux(本地 Docker)上工作。
Practically I wasn't able to make it work on OS X because of the double NAT layer you have to pass in order to get into the SSH service, and it looks like it's not possible to add extra interface to the Vagrant boot2docker box (Vagrant 1.7.2).
实际上我无法让它在 OS X 上工作,因为你必须通过双 NAT 层才能进入 SSH 服务,而且看起来不可能向 Vagrant boot2docker 框(Vagrant 1.7.2)。
回答by noisy
It's not yet here, but shortly this should no longer be a problem, since
它还没有出现,但很快这应该不再是问题,因为
Docker support will be introduced in PyCharm starting with PyCharm 4.1 EAP (beginning of April)
从 PyCharm 4.1 EAP(四月初)开始,将在 PyCharm 中引入 Docker 支持
来源:http: //blog.jetbrains.com/pycharm/2015/03/feature-spotlight-python-remote-development-with-pycharm/#comment-187772
回答by Fran K.
UPDATE: PyCharm 2017.1 has a solution for this problem, see this blog entry
更新:PyCharm 2017.1 有针对此问题的解决方案,请参阅此博客条目
Here is how I solved the problem. My circumstances are that I was assigned to do an intervention on a specific area of a web app that used docker-compose to create a set of four containers. Docker-compose is a kind of meta docker that manages multiple docker containers from one command. I did not want to mangle their existing setup since so many things depend on it. But since I was working on one specific part in one of the images I decided that I would extend one of the containers with ssh so that I could debug from PyCharm. Further, I wanted the app to run as normal when started and only by forcing it to quit and then connecting to it from PyCharm would I have a debuggable component. Here is what I did on my mac that uses boot2docker (on VirtualBox) to setup docker correctly.
这是我解决问题的方法。我的情况是,我被分配对使用 docker-compose 创建一组四个容器的 Web 应用程序的特定区域进行干预。Docker-compose 是一种元 docker,可以通过一个命令管理多个 docker 容器。我不想破坏他们现有的设置,因为很多事情都依赖于它。但是由于我正在处理其中一个图像中的一个特定部分,因此我决定使用 ssh 扩展其中一个容器,以便我可以从 PyCharm 进行调试。此外,我希望应用程序在启动时能正常运行,并且只有通过强制它退出然后从 PyCharm 连接到它,我才会有一个可调试的组件。这是我在使用 boot2docker(在 VirtualBox 上)正确设置 docker 的 mac 上所做的。
First, I need to extend the target container, called jqworker
. I am going to use "supervisior"
to do the heavy lifting of managing things.
首先,我需要扩展名为jqworker
. 我将用来"supervisior"
做管理事情的繁重工作。
FROM jqworker
# Get supervisor to control multiple processes, sshd to allow connections.
# And supervisor-stdout allows us to send the output to the main docker output.
RUN apt-get update && apt-get install -y supervisor openssh-server python-pip \
&& pip install supervisor-stdout \
&& mkdir -p /var/run/sshd \
&& mkdir -p /var/log/supervisor \
&& mkdir -p /etc/supervisor/conf.d
COPY ./supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# Fix up SSH, probably should rip this out in real deploy situations.
RUN echo 'root:soup4nuts' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
# Expose SSH on 22, but this gets mapped to some other address.
EXPOSE 22
# Replace old entrypoint with supervisiord, starts both sshd and worker.py
ENTRYPOINT ["/usr/bin/supervisord"]
Supervisor lets me run multiple tasks from one command, in this case the original command and SSHD. Yes, everyone says that SSHD in docker is evil and containers should this and that and blah blah, but programming is about solving problems, not conforming to arbitrary dicta that ignore context. We need SSH to debug code and are not deploying this to the field, which is one reason we are extending the existing container instead of adding this in to the deployment structure. I am running it locally so that I can debug the code in context.
Supervisor 允许我从一个命令运行多个任务,在这种情况下是原始命令和 SSHD。是的,每个人都说 docker 中的 SSHD 是邪恶的,容器应该这样那样和等等等等,但编程是关于解决问题,而不是遵守忽略上下文的任意口述。我们需要 SSH 来调试代码,而不是将其部署到现场,这是我们扩展现有容器而不是将其添加到部署结构中的原因之一。我在本地运行它,以便我可以在上下文中调试代码。
Here is the supervisord.conf
file, note that I am using the supervisor-stdout
package to direct output to supervisor instead of logging the data as I prefer to see it all in one place:
这是supervisord.conf
文件,请注意,我使用该supervisor-stdout
包将输出定向到主管,而不是记录数据,因为我更喜欢在一个地方查看所有内容:
[supervisord]
nodaemon=true
[program:sshd]
command=/usr/sbin/sshd -D
[program:worker]
command=python /opt/applications/myproject/worker.py -A args
directory=/opt/applications/myproject
stdout_events_enabled=true
stderr_events_enabled=true
[eventlistener:stdout]
command = supervisor_stdout
buffer_size = 100
events = PROCESS_LOG
result_handler = supervisor_stdout:event_handler
I have a build directory containing the above two files, and from a terminal in there I build the Dockerfile
with:
我有一个包含上述两个文件的构建目录,并从那里的终端构建Dockerfile
:
docker build -t fgkrqworker .
This adds it so that I can call it from docker
or docker-compose
. Don't skip the trailing dot!
这会添加它,以便我可以从docker
或调用它docker-compose
。不要跳过尾随点!
Since the app uses docker-compose
to run a set of containers, the existing WORKER
container will be replaced with one that solves my problems. But first I want to show that in another part of my docker-compose.yml
I define a mapping from the containers to my local hard drive, this is one of a number of volumes being mapped:
由于该应用程序用于docker-compose
运行一组容器,因此现有WORKER
容器将替换为解决我的问题的容器。但首先我想表明,在我的另一部分中,我docker-compose.yml
定义了从容器到本地硬盘驱动器的映射,这是被映射的多个卷之一:
volumes: &VOLUMES
? /Users/me/source/myproject:/opt/applications/myproject
Then the actual definition for my container, which references the above VOLUMES
:
然后是我的容器的实际定义,它引用了上述内容VOLUMES
:
jqworker: &WORKER
image: fgkrqworker
privileged: true
stdin_open: true
detach: true
tty: true
volumes:
<<: *VOLUMES
ports:
- "7722:22"
This maps the SSH port to a known port that is available in the VM, recall I am using boot2docker
which rides on VirtualBox, but the needs to be mapped out to where PyCharm can get at it. In VirtualBox, open the boot2docker
VM and choose Adapter 1
. Sometimes the "Attached to:" combo unselects itself, so watch for that. In my case it should have NAT
selected.
这将 SSH 端口映射到 VM 中可用的已知端口,回想一下我使用的boot2docker
是 VirtualBox 上的哪个端口,但需要映射到 PyCharm 可以访问它的位置。在 VirtualBox 中,打开boot2docker
VM 并选择Adapter 1
。有时“附加到:”组合会取消选择自身,因此请注意这一点。在我的情况下,它应该NAT
选择。
Click "Port Forwarding" and map the inner port to the a port on localhost, I choose to use the same port number. It should be something like:
单击“端口转发”并将内部端口映射到本地主机上的端口,我选择使用相同的端口号。它应该是这样的:
- Name:
ssh_mapped
; - Protocol:
TCP
; - Host IP:
127.0.0.1
; - Host Port:
7722
; - Guest IP:;
- Guest Port:
7722
- 姓名:
ssh_mapped
; - 协议:
TCP
; - 主机IP
127.0.0.1
:; - 主机端口:
7722
; - 访客IP:;
- 来宾端口:
7722
Note:be careful not to change the boot2docker ssh
setting or you will eventually be unable to start the VM correctly.
注意:请注意不要更改 boot2dockerssh
设置,否则您最终将无法正确启动 VM。
So, at this point we have a container that extends my target container. It runs ssh on port 22
and maps it to 7722
since other containers might want to use 22
, and is visible in the VirtualBox environment. VirtualBox maps 7722
to 7722
to the localhost and you can ssh into the container with:
所以,此时我们有一个扩展我的目标容器的容器。它在端口22
上运行 ssh并将其映射到,7722
因为其他容器可能想要使用22
,并且在 VirtualBox 环境中可见。VirtualBox 映射7722
到7722
本地主机,您可以通过 ssh 进入容器:
ssh root@localhost -p 7722
Which will then prompt for the password, 'soup4nuts' and you should be able to locate something specific to your container to verify that it is the right one and that everything works OK. I would not mess with root if I were deploying this anywhere but my local machine, so be warned. This is only for debugging locally and you should think twice or thrice about doing this on a live site.
然后它将提示输入密码“soup4nuts”,您应该能够找到特定于您的容器的内容,以验证它是正确的并且一切正常。如果我将它部署到本地机器以外的任何地方,我就不会惹恼 root,所以请注意。这仅用于本地调试,您应该三思而后行在实时站点上执行此操作。
At this point you can probably figure the rest of it out if you have used PyCharm's remote debugging. But here is how I set it up:
此时,如果您使用过 PyCharm 的远程调试,那么您可能会弄清楚其余部分。但这是我设置的方式:
First, recall that I have docker-compose.yml
mapping the project directory:
首先,回想一下我已经docker-compose.yml
映射了项目目录:
? /Users/me/source/myproject:/opt/applications/myproject
In my container /opt/applications/myproject
is actually /Users/me/source/myproject
on my local hard drive. So, this is the root of my project. My PyCharm sees this directory as the project root and I want PyCharm to write the .pycharm_helpers
here so that it persists between sessions. I am managing source code on the mac side of things, but PyCharm thinks it is a unixy box elsewhere. Yes, it is a bit of kludge until JetBrains incorporates a Docker solution.
在我的容器/opt/applications/myproject
中实际上是/Users/me/source/myproject
在我的本地硬盘上。所以,这是我项目的根。我的 PyCharm 将此目录视为项目根目录,我希望 PyCharm 将其写入.pycharm_helpers
此处,以便它在会话之间保持不变。我正在管理 mac 端的源代码,但 PyCharm 认为它是其他地方的 unixy box。是的,在 JetBrains 合并 Docker 解决方案之前,这有点麻烦。
First, go to the Project X/Project Structure and create a Content Root of the local mapping, in my case that means /Users/me/source/myproject
首先,转到 Project X/Project Structure 并创建本地映射的 Content Root,在我的情况下,这意味着 /Users/me/source/myproject
Later, come back and add .pycharm_helpers
to the excluded set, we don't want this to end up in source control or confuse PyCharm.
稍后,返回并添加.pycharm_helpers
到排除集,我们不希望这最终出现在源代码控制中或混淆 PyCharm。
Go to the Build, Execution, Deployment tab, pick Deployment and create a new Deployment of SFTP type. The host is localhost, the port 7722
, the root path is /opt/applications/myproject
and the username is root
and password is soup4nuts
and I checked the option to save the password. I named my Deployment 'dockercompose' so that I would be able to pick it out later.
转到构建、执行、部署选项卡,选择部署并创建一个新的 SFTP 类型部署。主机是 localhost,端口7722
是根路径/opt/applications/myproject
,用户名是root
,密码是soup4nuts
,我选中了保存密码的选项。我将我的部署命名为“dockercompose”,以便我以后可以选择它。
On the Deployment Mappings tab I set the local path to /Users/me/source/myproject
and deployment and web path to a single '/' but since my code doesn't correspond to a URL and I don't use this to debug, it is a placeholder in the Web Path setting. I don't know how you might set yours.
在“部署映射”选项卡上,我将本地路径/Users/me/source/myproject
和部署路径和 Web 路径设置为单个“/”,但由于我的代码与 URL 不对应,而且我不使用它进行调试,因此它是 Web 中的占位符路径设置。我不知道你会如何设置你的。
On the Project X/Project Interpreter tab, create a new Remote Python Interpreter. You can pick the Deployment Configuration and choose the dockercompose
configuration we created above. The host URL should fill in as ssh://root@localhost:7722
and the Python Interpreter Path will likely be /usr/bin/python
. We need to set the PyCharm Helpers Path as the default will not survive the container being redone. I actually went to my project local directory and created a .pycharm_helpers
directory in the root, then set the path here as /opt/applications/myproject/.pycharm_helpers
and when I hit the OK button it copied the files "up" to the directory. I don't know if it will create it automatically or not.
在 Project X/Project Interpreter 选项卡上,创建一个新的远程 Python 解释器。您可以选择部署配置并选择dockercompose
我们上面创建的配置。主机 URL 应填写为ssh://root@localhost:7722
,Python 解释器路径可能为/usr/bin/python
. 我们需要设置 PyCharm Helpers 路径,因为默认值不会在容器重做后继续存在。我实际上去了我的项目本地目录并.pycharm_helpers
在根目录中创建了一个目录,然后在此处设置路径/opt/applications/myproject/.pycharm_helpers
,当我点击“确定”按钮时,它将文件“向上”复制到目录中。我不知道它是否会自动创建它。
Don't forget that the .pycharm_helpers
directory should probably be excluded on the project roots tab.
不要忘记该.pycharm_helpers
目录可能应该被排除在项目根选项卡上。
At this point you can go to the Build, Execution, Deployment tab, and under Console/Python Console, pick the remote interpreter we created above and set the working directory to /opt/applications/myproject
and you can run your Python Console in the container if you like.
此时,您可以转到 Build、Execution、Deployment 选项卡,然后在 Console/Python Console 下,选择我们上面创建的远程解释器并将工作目录设置为/opt/applications/myproject
,如果您愿意,您可以在容器中运行 Python Console。
Now you need to create a Run Configuration so that you can remotely debug your python code. Make a new Python configuration and set the script to the one that used to start the python code in the container. Mine, from the supervisor setup, above is:
现在您需要创建一个运行配置,以便您可以远程调试您的 Python 代码。进行新的 Python 配置并将脚本设置为用于在容器中启动 Python 代码的脚本。我的,从主管设置,上面是:
/opt/applications/myproject/worker.py -A args
So I set the script to /opt/applications/myproject/worker.py
and the parameters to -A args
.
所以我将脚本设置为/opt/applications/myproject/worker.py
,参数设置为-A args
。
Choose the remote interpreter we created above, and the working directory as needed, for me it is /opt/applications/myproject
and for me that does the job.
选择我们上面创建的远程解释器,并根据需要选择工作目录,对我来说,这就是/opt/applications/myproject
我的工作。
Now I want to enter my container and stop the worker.py
script so I can start up a debug version. Of course, if you like you can ignore running the script by default and only use the container for debugging.
现在我想进入我的容器并停止worker.py
脚本,以便我可以启动调试版本。当然,如果你愿意,你可以默认忽略运行脚本,只使用容器进行调试。
I could open a ssh session to stop the script, but docker provides a useful command that will do the work for me by passing it into the environment.
我可以打开一个 ssh 会话来停止脚本,但是 docker 提供了一个有用的命令,它将通过将它传递到环境中来为我完成工作。
$> docker exec -i -t supervisorctl stop worker
As my process is named 'worker'. Note that you can restart by replacing the stop
command with start
.
因为我的过程被命名为“工人”。请注意,您可以通过将stop
命令替换为 来重新启动start
。
Now, in PyCharm start a debug session with the Run Configuration created above. It should connect and start things up and give you console output in the window. Since we killed the one that Supervision originally started it is no longer connected.
现在,在 PyCharm 中使用上面创建的运行配置启动调试会话。它应该连接并启动并在窗口中为您提供控制台输出。由于我们杀死了监督最初启动的那个,它不再连接。
This was a seat of the pants operation, so there may be errors and incorrect assumptions I didn't notice. Particularly, the PyCharm setup required a few iterations, so the order may be incorrect, try going through it again if it fails. This is a lot of stuff and easy to skip something critical.
这是一个靠得住的操作,所以可能存在我没有注意到的错误和不正确的假设。特别是 PyCharm 设置需要几次迭代,所以顺序可能不正确,如果失败,请重新尝试。这是很多东西,很容易跳过一些关键的东西。
回答by 3ka5_cat
If all you need is to debug code which is launched inside docker container, you could use pycharm's python debug serverfeature. As for me, it is less troublesome way than accessing remote interpreter via SSH. Drawback of this solution is that for auto-complete and all this kind of stuff you should have local copy of container's interpreter and mark it as project's interpreter (works for auto-complete, but i'm not sure that it's possible to debug code from third-party libs in such case) or make container's interpreter files visible to pycharm (not tested at all). Also note that Python debug server is feature of Professional edition.
如果您只需要调试在 docker 容器内启动的代码,您可以使用 pycharm 的python 调试服务器功能。对我来说,这比通过 SSH 访问远程解释器更麻烦。此解决方案的缺点是,对于自动完成和所有此类内容,您应该拥有容器解释器的本地副本并将其标记为项目的解释器(适用于自动完成,但我不确定是否可以从在这种情况下,第三方库)或使容器的解释器文件对 pycharm 可见(根本未测试)。另请注意,Python 调试服务器是专业版的功能。
What you should do for debugging via Python debug server:
您应该通过 Python 调试服务器进行调试:
1) make sure that directory with your project is added into container. It could look like this line in Dockerfile:
1)确保将项目所在的目录添加到容器中。它可能看起来像 Dockerfile 中的这一行:
ADD . /path/in/container
ADD . /path/in/container
2) copy pycharm-debug.egg
(pycharm-debug-py3k.egg
for Python3) from directory where pycharm is installed on your host to directory in container, which is in container's PYTHONPATH.
Path to pycharm-debug.egg on developer's host could be:
2)将pycharm-debug.egg
(pycharm-debug-py3k.egg
对于Python3)从pycharm安装在主机上的目录复制到容器中的目录,该目录位于容器的PYTHONPATH中。开发者主机上 pycharm-debug.egg 的路径可能是:
- for Mac:
/Applications/PyCharm.app/Contents/pycharm-debug.egg
- for Linux:
/opt/pycharm/pycharm-debug.egg
- 对于 Mac:
/Applications/PyCharm.app/Contents/pycharm-debug.egg
- 对于 Linux:
/opt/pycharm/pycharm-debug.egg
3) create Run/Debug configuration for launching Python debug server on host as described at To configure a remote debug server
section of docs. Port is any host's port of your choice, but IP is address at which host is accessible from container. It could be:
3) 如文档To configure a remote debug server
部分所述,创建运行/调试配置以在主机上启动 Python 调试服务器。端口是您选择的任何主机的端口,但 IP 是可从容器访问主机的地址。它可能是:
- if container run via boot2docker, likely, IP is 192.168.99.1 -- host's address at Host-only network with vbox machine
- if host is Linux, IP can be found via
ifconfig
, for me it is:
- 如果容器通过 boot2docker 运行,IP 很可能是 192.168.99.1——主机地址在带有 vbox 机器的 Host-only 网络上
- 如果主机是 Linux,IP 可以通过 找到
ifconfig
,对我来说是:
docker0 Link encap:Ethernet HWaddr 56:84:7a:fe:97:99 inet addr:172.17.42.1 Bcast:0.0.0.0 Mask:255.255.0.0
docker0 Link encap:Ethernet HWaddr 56:84:7a:fe:97:99 inet addr:172.17.42.1 Bcast:0.0.0.0 Mask:255.255.0.0
Also, don't forget to specify path mappings between project's path at developer's host and project's path at container.
另外,不要忘记指定开发者主机上的项目路径和容器上的项目路径之间的路径映射。
This blog post also could be helpful for current step
4) launch this created configuration (for example, via Debug
button, right from Run
one)
4)启动这个创建的配置(例如,通过Debug
按钮,从Run
一个开始)
5) create python script which would launch your project and add the following code for debug initialization as first lines of this script. (make sure that pycharm-debug.egg
is in PYTHONPATH, or this code couldn't import pydevd
):
5)创建将启动您的项目的python脚本,并添加以下用于调试初始化的代码作为该脚本的第一行。(确保它pycharm-debug.egg
在 PYTHONPATH 中,否则此代码不能import pydevd
):
import pydevd pydevd.settrace('172.17.42.1', suspend=False, port=8765, stdoutToServer=True, stderrToServer=True)
import pydevd pydevd.settrace('172.17.42.1', suspend=False, port=8765, stdoutToServer=True, stderrToServer=True)
6) Finally, you could set breakpoints and launch your application from host, in container via created script. For example:
6) 最后,您可以通过创建的脚本在容器中设置断点并从主机启动您的应用程序。例如:
docker-compose run 'container_name' python 'script_name' 'args'
docker-compose run 'container_name' python 'script_name' 'args'
On start, yours launching script will connect to Python debug server, which is running on host, and stop on breakpoints. Debugger features will be available as usual.
启动时,您的启动脚本将连接到在主机上运行的 Python 调试服务器,并在断点处停止。调试器功能将照常提供。
回答by Dobes Vandermeer
With PyCharm 5 they added support for docker. You must have your docker configured in docker-machine.
在 PyCharm 5 中,他们增加了对 docker 的支持。您必须在 docker-machine 中配置您的 docker。
If you don't already use docker-machine you can connect to an existing machine using the generic machine engine and ssh into a vagrant VM or to localhost if you aren't running things in a VM. I didn't find a way around the ssh to localhost unfortunately.
如果您还没有使用 docker-machine,您可以使用通用机器引擎连接到现有机器,并 ssh 连接到流浪虚拟机或本地主机(如果您不在虚拟机中运行)。不幸的是,我没有找到绕过 ssh 到 localhost 的方法。
I haven't found a way to mount volumes into the docker image they use, to share files with my dev tree, but it might be possible.
我还没有找到一种方法将卷挂载到他们使用的 docker 映像中,与我的开发树共享文件,但它可能是可能的。
回答by Marc
Steps specific to PyCharm Professional Edition 2017.2(however they may work with PyCharm CE)
特定于 PyCharm 专业版 2017.2 的步骤(但它们可能适用于 PyCharm CE)
Here are a couple steps I took to get my setup working
以下是我为使设置正常工作而采取的几个步骤
Step 1: Environment
第 1 步:环境
A few assumptions of the structure of your (or anyone who might be reading this) project:
对您(或可能正在阅读本文的任何人)项目结构的一些假设:
bleh
├── README.md
├── api
│?? ├── Dockerfile <---- this is the one we want to debug
│?? ├── config.example.ini
│?? └── src
│?? ├── __init__.py <---- this is a pycharm project
│?? ├── __main__.py <---- this is a pycharm project
│?? └── ...
├── proxy
│?? ├── Dockerfile
│?? ├── config.example.ini
│?? └── src
│?? ├── ...
│?? └── ...
├── webserver
│?? ├── Dockerfile
│?? ├── config.example.ini
│?? └── src
│?? ├── ...
│?? └── ...
├── frontend
│?? ├── Dockerfile
│?? ├── config.example.ini
│?? └── src
│?? ├── ...
│?? └── ...
├── db
│?? ├── Dockerfile
│?? ├── ...
│?? └── migrations
│?? ├── ...
│?? └── ...
└── docker-compose.yml
- NoteI'm using
bleh
as a my project name only as an example. - NoteWe're also going to assume that this project has the absolute location of
/Users/myfunkyusername/Projects/bleh
. - NoteObviously this is all random as far as naming and location is concerned, please make adjustments specific to your system/project
- NoteWe're also going to assume that you wish to live debug the
api
service as shown later in thedocker-compose.yml
file NoteWe're also going to assume a content of your
api
's one and onlyDockerfile
is as suchFROM python ADD config.example.ini /etc/bleh/config.ini RUN chmod +x /usr/bin/bleh COPY ./src /usr/bin/bleh WORKDIR /usr/bin/bleh RUN pip install -r requirements.txt CMD ["sh", "-c", "python -m bleh --cfg=/etc/bleh/config.ini"]
NoteWe're assuming your one and only
docker-compose.yml
has these contentsversion: '2' services: api: build: context: ./api depends_on: - db expose: - "8080" networks: - default frontend: build: context: ./frontend ports: - "80:7000" networks: - default webserver: build: context: ./webserver depends_on: - frontend networks: - default proxy: build: context: ./proxy ports: - "80:80" - "443:443" depends_on: - webserver - api networks: - default db: build: context: ./db expose: - "3306" networks: - default networks: default: driver: bridge
- 请注意,我
bleh
仅将我的项目名称用作示例。 - 注意我们还将假设此项目具有
/Users/myfunkyusername/Projects/bleh
. - 注意显然,就命名和位置而言,这都是随机的,请针对您的系统/项目进行调整
- 注意我们还将假设您希望实时调试
api
服务,如docker-compose.yml
文件后面所示 注意我们还将假设您的
api
's one and only 内容Dockerfile
是这样的FROM python ADD config.example.ini /etc/bleh/config.ini RUN chmod +x /usr/bin/bleh COPY ./src /usr/bin/bleh WORKDIR /usr/bin/bleh RUN pip install -r requirements.txt CMD ["sh", "-c", "python -m bleh --cfg=/etc/bleh/config.ini"]
注意我们假设你的只有
docker-compose.yml
这些内容version: '2' services: api: build: context: ./api depends_on: - db expose: - "8080" networks: - default frontend: build: context: ./frontend ports: - "80:7000" networks: - default webserver: build: context: ./webserver depends_on: - frontend networks: - default proxy: build: context: ./proxy ports: - "80:80" - "443:443" depends_on: - webserver - api networks: - default db: build: context: ./db expose: - "3306" networks: - default networks: default: driver: bridge
Step 2: Create Docker-Machine
第 2 步:创建 Docker-Machine
Create docker-machine specifically for the bleh
project
专门为bleh
项目创建docker-machine
docker-machine create bleh
Step 3: connect remote interpreter
第三步:连接远程解释器
- From
PyCharm
/Preferences
/Build, Execution, Deployment
/Docker
click+
- Select the
Docker machine
radio button and highlightbleh
's docker machine in the pull down - Select
Apply
- From
PyCharm
/Preferences
/Project:bleh
/Project Interpreter
- Click the gear icon on the far right of the
Project Interpreter
field and selectAdd Remote
- Select
Docker
radio button - With
Server
field, select previously created docker machine for this project - Select the docker image that holds your desired python interpreter for this project (e.g
bleh_api
) - No change to the
Python interpreter path
needed - Click
OK
- 从
PyCharm
/Preferences
/Build, Execution, Deployment
/Docker
点击+
- 选择
Docker machine
单选按钮并bleh
在下拉菜单中突出显示docker machine - 选择
Apply
- 来自
PyCharm
/Preferences
/Project:bleh
/Project Interpreter
- 单击
Project Interpreter
字段最右侧的齿轮图标并选择Add Remote
- 选择
Docker
单选按钮 - 使用
Server
字段,选择之前为此项目创建的 docker 机器 - 选择保存此项目所需的 Python 解释器的 docker 映像(例如
bleh_api
) - 无需更改
Python interpreter path
所需 - 点击
OK
Step 4: configure remote debugger
第四步:配置远程调试器
- From
Run
/Edit Configurations
select+
to add a configuration - Select
Python
- With
Script
field, use location of script file on the docker container that will be run (in this example it's/usr/bin/bleh/__main__.py
as we're giving the absolute location of our target script) - With
Script parameters
field, supply CLI parameters, if any (mimics theDockerfile
's lastCMD
command, which is--cfg=/etc/bleh/config.ini
) - With
Python Interpreter
field, select your previously established remote python interpreter - With
Working directory
field, select the directory whereScript
is located within the Docker container (e.g/usr/bin/bleh
) - With
Path mappings
field, click the...
and select local (e.g/Users/myfunkyusername/Projects/bleh/api/src
) and remote (e.g/usr/bin/bleh
) as above - With
Docker container settings
field, click...
- ensure you have the correct docker container selected (e.g.
bleh_api:latest
) - Add port binding container/host that mimics what you have the in
Dockerfile
(e.g 8080/8080 and expose to0.0.0.0
using thetcp
protocol, now I haven't shown what your app structure is, but let's assume that you were sane and within your app are also specifying8080
as the port where your'e serving your data. - Add volume bindings container/host
/usr/bin/bleh
//Users/myfunkyusername/Projects/bleh/api/src
- ensure
Network mode
(thanks Piotr) is set to<name_of_project_directory>_<name_of_network_from_compose_file>
(e.gbleh_default
, you can confirm withdocker network ls
from within the correctdocker-machine
)
- ensure you have the correct docker container selected (e.g.
- 从
Run
/Edit Configurations
选择+
添加配置 - 选择
Python
- 使用
Script
字段,使用将运行的 docker 容器上脚本文件的位置(在此示例中,/usr/bin/bleh/__main__.py
因为我们提供了目标脚本的绝对位置) - 使用
Script parameters
字段,提供 CLI 参数(如果有)(模仿Dockerfile
的最后一个CMD
命令,即--cfg=/etc/bleh/config.ini
) - 使用
Python Interpreter
字段,选择您之前建立的远程 python 解释器 - 使用
Working directory
字段,选择Script
位于 Docker 容器内的目录(例如/usr/bin/bleh
) - 与
Path mappings
字段,单击...
并选择本地(例如/Users/myfunkyusername/Projects/bleh/api/src
)和远程(例如/usr/bin/bleh
),如上 - 使用
Docker container settings
字段,单击...
- 确保您选择了正确的 docker 容器(例如
bleh_api:latest
) - 添加端口绑定容器/主机以模拟您所拥有的内容
Dockerfile
(例如 8080/8080 并公开0.0.0.0
使用该tcp
协议,现在我还没有展示您的应用程序结构是什么,但让我们假设您是理智的并且在您的应用程序中也是指定8080
为您提供数据的端口。 - 添加卷绑定容器/主机
/usr/bin/bleh
//Users/myfunkyusername/Projects/bleh/api/src
- 确保
Network mode
(感谢 Piotr)设置为<name_of_project_directory>_<name_of_network_from_compose_file>
(例如bleh_default
,您可以docker network ls
从正确的内部确认docker-machine
)
- 确保您选择了正确的 docker 容器(例如
Step 5: Bask in the Sun or Bash your head some more
第 5 步:晒太阳或多敲你的头
These are the steps that got me to a working docker and PyCharm setup.
这些是使我进入工作 docker 和 PyCharm 设置的步骤。
I don't pretend to be correct in each of these steps. I will gladly update any errors/improvements you find.
我不会假装在每个步骤中都是正确的。我很乐意更新您发现的任何错误/改进。