DEV Community

jicking bebiro
jicking bebiro

Posted on

Dockerize a Nodejs Express Api with VS Code

With VS Code (and Docker extension) it is much easier to dockerize a nodejs express app and monitor containers if you dont like to do it all via terminal like myself.

Create a simple nodejs express api

create a new folder then open it on VS Code.

mkdir node-docker
cd nodeapp
code .
Enter fullscreen mode Exit fullscreen mode

Initialize a node project, and set the defaults.

npm init
Enter fullscreen mode Exit fullscreen mode

then install express

npm i express
Enter fullscreen mode Exit fullscreen mode

in project root, create app.js file.

const express = require('express');
const app = express();

const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(PORT,() => {
  console.log(`Server listening on Port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Add a new script on package .json to start api.
For simplicity copy this package.json

{
  "name": "nodedocker",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "4.19.2"
  }
}
Enter fullscreen mode Exit fullscreen mode

Running npm run start will run api on port 3000.

Image description

Once confirmed terminate running app to free port 3000 on local machine as leaving it running prevents you from running your docker instance (this happens to me a lot).

Dockerize express api

Install docker vscode extension

Using Ctrl + shift + p , to open command pallete. then run
> Docker: Add Docker Files to Workspace...

You can leave options to default as it will automatically detects your platform (Nodejs) and creates vs code launch configuration for debugging.

Image description

By default It will create a Docker file, 2 docker compose (another one for debug) ,handy docker ignore and vs code launch settings.

Image description

For simplicity, you can ryun docker compose via file system pane menu. Select docker compose file and right click to open context menu. Then click compose up to spawn a container instance.

Image description

You can then check on docker panel that container is running.

Image description


I might write next

Top comments (0)