Dockerize a Nodejs Express Api with VS Code
jicking bebiro
Posted on March 28, 2024
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 .
Initialize a node project, and set the defaults.
npm init
then install express
npm i express
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}`);
});
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"
}
}
Running npm run start will run api on port 3000.
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.
By default It will create a Docker file, 2 docker compose (another one for debug) ,handy docker ignore and vs code launch settings.
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.
You can then check on docker panel that container is running.
I might write next
- mount virtual path
- add db to compose
- Vscode dev container
Posted on March 28, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.