A codespace is a development environment that’s hosted in the cloud.

GitHub Codespaces overview

Codespace environments are created using development containers (aka dev containers) hosted on a virtual machine. There is an open specification for development containers. Development containers are supported, for example, by Visual Studio Code (with the help of the Dev Containers extension maintained by Microsoft).

Although Microsoft maintains both projects, GitHub Codespaces has very interesting quirks, and it does not support Dev Containers the way VSCode does.

One of these quirks relates to automatic port forwarding. Port forwarding gives you access to TCP ports running within a codespace. You can specify the ports you want to forward automatically with the help of the forwardPorts property. This works flawlessly in VSCode but does not always work in a codespace.

Let us, for example, use this configuration to create a development container:

{
    "name": "Sample Dev Container",
    "image": "nginx",
    "forwardPorts": [80]
}

If we create a codespace from this configuration, we will see something like this:

GitHub forwards the port automatically

So far, so good. Now, let us change the configuration a bit by introducing a mount:

{
    "name": "Sample Dev Container",
    "image": "nginx",
    "forwardPorts": [80],
    "mounts": [
        {
            "type": "volume",
            "source": "www",
            "target": "/var/www"
        }
    ]
}

And if we open this configuration in a codespace, we will discover that the automatic port forwarding ceased to work:

Automatic port forwarding does not work if you have volume mounts

Automatic port forwarding still works if you have bind mounts, but Codespaces service does not support bind mounts 🙂

I don’t know what automatic port forwarding has to do with volume mounts, but the fact is that this combination does not work.

Let us try something else:

{
    "name": "Sample Dev Container",
    "image": "nginx",
    "forwardPorts": [80],
    "postCreateCommand": "ls -lha"
}

In this scenario, once the dev container has been assigned to a user for the first time, we run the ls -lha command. Everything works fine, GitHub forwards ports.

But what happens if we change the postCreateCommand to use object syntax?

{
    "name": "Sample Dev Container",
    "image": "nginx",
    "forwardPorts": [80],
    "postCreateCommand": {
        "list": "ls -lha"
    }
}

Yes, you have guessed it: automatic port forwarding will not work anymore 🙂 It is a mystery why.

I filed a bug report with GitHub almost a week ago, but the developers are a bit slow to react.

The moral of this story is that you need to test your dev containers in all environments you will support. There is nothing new, though.

GitHub Codespaces and Automatic Port Forwarding
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *