Attach Visual Studio Code to a Running Container
Scenario
Visual Studio Code provides developers with unprecedent ability of remote development. In this I’m going to talk about how to attach VSCode to remote server, and remote docker container. For the latter, there might be an extra problem that, by default, VSCode will connect to the container as root, while we may want another profile used. So I’ll cover this also.
Connecting To Remote Server
It is most easy to connect to a remote server. Simply click the terminal icon on the bottom left cornet, and choose “Connect to Host”.
Then, you can choose to add a new SSH host like user@host
, or select “Configure SSH Hosts…”, and choose the config under the current user. (Here is the first one with highlight.)
If you choose to modify the configuration, you should add a new section like this in the config
.
1 | Host {Display name} |
Of course, you can use password or SSH key as your favor.
Attaching to a Running Container
Attaching by default
As container will be running on a host machine, we have to connect to the host first. If the container runs on remote machine, just connect to it first, and then do as what you do on local machine.
First, you need the Docker extension to help you manage all containers.
After installation, you will see a Docker icon on the activity bar, and you can see all your docker containers and their status in this tab.
Then, you can just right click on any running container, and select “Attach Visual Studio Code”, and there you go.
By this, you will log in to the docker with default root user.
Customized Attaching
However, if you want to attach to a specific container with users other than root, you need one more step. After attaching to the container, press “F1”, then enter “Dev Containers: Open Named Container Configuration File”.
This command can only be found in VSCode opened in a container.
Don’t know how to create a new user? See Create Sudo-Enabled User on Linux. 😉
In the opened configuration file, you can add these minimal options. You can choose where to start up by changing workspaceFolder
, and login as remoteUser
.
1 | { |
For more information on this configuration file, see Attach to a running container.
For running container, you should add named configuration file for the container, not devcontainer.json
in the host. And you should change remoteUser
instead of containerUser
.
Epilogue
Well, I guess this is it. Good luck! 🫡