Search code examples
.netlinux.net-coreubuntu-14.04remote-debugging

Debugging an already-running Docker Linux .NET Core container with Visual Studio 2017


With Visual Studio, when I create a .NET Core application and run it in Linux container, I can easily debug it using Visual Studio 2017.

But when I run the same image instance (release version) using docker run from the command line, I am not able to find a way in Visual Studio 2017 to attach to that instance.

How does Visual Studio do that and how can I do same for an already-running Docker Linux .NET Core container? Also, how can I do the same if the Docker image instance is running on a remote Linux machine?

A few concrete steps with an example will be helpful.


Solution

  • Having read Ankush's blog post, how about this:

    If your service is based off of the microsoft/dotnet image, create a new Dockerfile based on the same image, and install the debugger, ssh and unzip.

    FROM microsoft/dotnet
    
    RUN apt-get update && apt-get -y install openssh-server unzip
    
    RUN mkdir /var/run/sshd && chmod 0755 /var/run/sshd
    RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin without-password/g' /etc/ssh/sshd_config
    RUN sed -i 's/#StrictModes yes/StrictModes no/g' /etc/ssh/sshd_config
    
    RUN service ssh restart
    
    RUN mkdir /root/.vs-debugger && chmod 0755 /root/.vs-debugger
    RUN curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v vs2017u1 -l /root/.vs-debugger/
    
    EXPOSE 22
    

    Build and push this to your registry.

    docker build -t myregistry/dotnetdebugger .
    docker push myregistry/dotnetdebugger
    

    Next ensure that your service's build is outputting the PDB files as portable PDB files. See Off-road Debugging of .NET Core on Linux or OS X from Visual Studio.

    And ensure that the PDB files are included with the DLL files when you build your service's Docker image. Or better yet, volume mount an artefact directory with the PDB files in when you start your side car container.

    Then when your container is running and you decide that you need to debug it, you can attach the debugger container as a side car container to the service:

    docker run -d -p 10222:22 --pid container:<container name>  myregistry/dotnetdebugger
    

    Then in Visual Studio, go to menu ToolsOptionsCrossplatformConnection Manager - and add a new connection. Specify the IP address or hostname of the sidecar container and 10222 as the port (the one in the docker run command), and root as the user without a password.

    When you are done, you can simply shut down the sidecar container, leaving your service container running, and not exposing anything that is not needed for the general operation of your service.