【问题标题】:How to use VSCode with the existing docker container如何将 VSCode 与现有的 docker 容器一起使用
【发布时间】:2022-11-27 10:45:47
【问题描述】:

我做了一个 Python+Django+git docker 容器。 现在,我想使用 VSCode“附加到正在运行的容器..”来开发(即运行和调试)内部的 Python 应用程序。 这是个好主意吗?或者最好只设置 VSCode 在容器内运行应用程序? 我不希望 VSCode 自己制作一个 docker 容器。 谢谢。

我尝试“附加到正在运行的容器..”但出现“错误 xhr 失败...”等。

【问题讨论】:

    标签: python docker visual-studio-code


    【解决方案1】:

    Visual Studio Code 和 Docker Desktop 各自提供称为“Dev Containers”(VSCode)或“Dev Environments”(DD)或 CodeSpaces(GitHub)的功能

    在这种方法中,通过扫描源并生成包含开发工具链的容器来创建 Docker 容器。然后 Visual Studio 附加到容器,并允许您进行开发,即使您没有 node/python3/dotnet/etc。安装在您的开发 PC 上。

    xhr 错误表示下载扫描图像时出现问题,或者您的项目有其他问题。 如果扫描找不到图像,可以创建一个可选的 Dockerfile,该文件通常保存在 .devcontainers / .devenvironments 文件夹中,具体取决于您使用的是 Docker / VSCode / GitHub / 其他文件夹。

    您的项目可能还有一个(或多个)Dockerfile,用于将正在运行的应用程序打包为 docker 映像,所以如果您最终得到 2 个,请不要感到困惑。这不是问题,而且确实是预期的。

    【讨论】:

    • 谢谢您的回答。我想使用我自己的 docker 容器。例如,有可能使用 PyCharm Community。独立于 VSCode 及其插件。也许有一个例子如何使用这样的自制容​​器在里面运行和调试应用程序?
    【解决方案2】:

    我使用这样的环境在容器内开发 python 应用程序。

    image_create.sh # script to create image to use it local and on the server
    
    image_dockerfile # dockerfile with script how to create an image
    
    container_create.sh  # create named container from image
    
    container_restart.sh # restart existing container
    
    container_stop.sh  # stop existing container
    

    例子:

    image_docker 文件:

    FROM python:3.9.15-slim-bullseye
    USER root
    RUN pip3 install requests telethon
    RUN apt-get update
    RUN apt-get --assume-yes install git
    

    image_create.sh :

    docker rmi python_find_a_job:lts
    docker build . -f python_find_a_job -t python_find_a_job:lts
    

    container_create.sh :

    docker rm -f python_find_a_job
    docker run -t -d --name python_find_a_job -i python_find_a_job:lts
    docker ps -aq
    

    container_restart.sh :

    docker container restart python_find_a_job
    docker ps -aq
    

    容器停止.sh :

    docker stop python_find_a_job
    docker ps -aq
    

    对于 VS 代码:

    a) 准备文件(见上文)。

    b) 运行:

    image_create.sh

    容器创建.sh

    c) 在 VSCode 中打开项目文件夹

    d) 单击左下方绿色/附加到正在运行的容器/选择容器名称 (python_find_a_job)。

    e) 克隆存储库。

    f) 安装扩展“Python”。

    现在您可以在容器内运行和调试。

    下班以后:

    container_stop.sh

    上班前:

    container_restart.sh

    混帐拉

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 2016-06-11
      • 2019-11-22
      • 1970-01-01
      • 2020-08-30
      • 2014-03-10
      • 2021-02-11
      • 1970-01-01
      • 2018-11-08
      相关资源
      最近更新 更多