How to auto start node server after creating VS Code Development Container?

Viewed 534

I am using VS Code's feature to create development containers for my services. Using the following layout, I've defined a single service (for now). I'd like to automatically run my node project after the container is configured to listen for http requests but haven't found the best way to do so.

My Project Directory

  • project-name
    • .devcontainer.json
    • package.json (etc)
  • docker-compose.yaml

Now in my docker-compose.yaml, I've defined the following structure:

version: '3'

services:
    project-name:
        image: node:14
        command: /bin/sh -c "while sleep 1000; do :; done"
        ports: 
            - 4001:4001
        restart: always
        volumes:
            - ./:/workspace:cached

Note how I need to have /bin/sh -c "while sleep 1000; do :; done" as the service command, which is required according to VS Code docs so that the service doesn't close?

Within my .devcontainer.json:

{
    "name": "My Project",
    "dockerComposeFile": [
        "../docker-compose.yaml"
    ],
    "service": "project-name",
    "shutdownAction": "none",
    "postCreateCommand": "npm install",
    "postStartCommand": "npm run dev" // this causes the project to hang while configuring?
    "workspaceFolder": "/workspace/project-name"
}

I've added a postCreateCommand to install dependencies, but I also need to run npm run dev to have my server listen for requests. However, if I add this command in the postStartCommand, the project does build and run, but it technically hangs on Configuring Dev Server (with a spinner at the bottom of VS Code) since this starts my server and the script doesn't "exit", so I feel like there should be a better way to trigger the server to run after the container is set up?

enter image description here

1 Answers

See https://code.visualstudio.com/remote/advancedcontainers/start-processes

In other cases, you may want to start up a process and leave it running. This can be accomplished by using nohup and putting the process into the background using &. For example:

"postStartCommand": "nohup bash -c 'your-command-here &'"

I just tried it, and it works for me - it removes the spinning "Configuring Dev Container" that I also saw. However, it does mean the process is running in the background so your logs will not be surfaced to the devcontainer terminal. I got used to watching my ng serve logs in that terminal to know when compilation was done, but now I can't see them. Undecided if I'll switch back to the old way. Having the Configuring Dev Container spinning constantly was annoying but otherwise did not obstruct anything that I could see.

Related