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”.

image-20240225163215722

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.)

image-20240225163442686

If you choose to modify the configuration, you should add a new section like this in the config.

1
2
3
Host {Display name}
HostName {Host IP}
User {Login user}

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.

image-20240225164055129

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.

image-20240225164357230

Then, you can just right click on any running container, and select “Attach Visual Studio Code”, and there you go.

image-20240225164536500

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
2
3
4
5
6
7
8
9
10
{
// Default path to open when attaching to a new container.
"workspaceFolder": "/path/to/workspace",
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.defaultProfile.linux": "bash"
},
// Container user VS Code should use when connecting
"remoteUser": "username"
}

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! 🫡