This blog post shows how you can debug a simple Node.js application running in a Docker container. The tutorial is laid out in a fashion that allows you to use it as a reference while you’re building your own Node.js application and is intended for readers who have prior exposure to JavaScript programming and Docker. Prerequisites 1. . For details about installing Docker, refer to the page. Docker Install Docker 2. 10 or higher. To check out if Node.js is installed on your computer, fire up a terminal window and type the following command: Node.js node -v If Node.js is already installed, you'll see something like the following: v10.15.3 If Node.js is not installed, you can download the installer from the page. Download 3. . For details on how to install Visual Studio, refer to the page. Microsoft Visual Studio Install Visual Studio Initializing Your Todo Application For the scope of this tutorial, we’ll create a bare-bones todo list that allows users to add and delete tasks. There will be a small bug in the application and we’ll use Visual Studio Code to debug the code and fix the issue. The knowledge you’ll acquire in this tutorial will help you debug your own applications. Let’s get started. 1. Fire up a new terminal window, move into your projects directory, and then execute the following command: mkdir MyTodoApp && MyTodoApp cd 2. Initialize the project with: npm init -y This will output something like the following: Wrote to /Users/ProspectOne/Documents/MyTodoApp/package.json: { : , : , : , : , : { : }, : [], : , : } "name" "MyTodoApp" "version" "1.0.0" "description" "" "main" "index.js" "scripts" "test" "echo \"Error: no test specified\" && exit 1" "keywords" "author" "" "license" "ISC" Creating a Bare-bones Todo Application We’ll build our todo application using , a fast, unopinionated, minimalist web framework for Node.js. Express was designed to make developing websites much easier and it’s one of the most popular Node.js web frameworks. Express 1. Install and a few other prerequisites by entering the following command: express npm install express body-parser cookie-session ejs --save > ejs@3.0.1 postinstall /Users/ProspectOne/Documents/ /MyTodoApp/node_modules/ejs > node ./postinstall.js Thank you installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/) npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN MyTodoApp@1.0.0 No description npm WARN MyTodoApp@1.0.0 No repository field. + ejs@3.0.1 + body-parser@1.19.0 + express@4.17.1 + cookie-session@1.3.3 added 55 packages from 39 contributors and audited 166 packages 6.533s found 0 vulnerabilities test for in 2. Create a file called with the following content: app.js const express = require( ) const app = express() const bodyParser = require( ) const session = require( ) const urlencodedParser = bodyParser.urlencoded({ extended: }) const port = 3000 app.use(session({ secret: process.env.SECRET })) .use( (req, res, next) { next() }) .get ( , (req, res) { res.render( , { todolist: req.session.todolist }) }) .post ( , urlencodedParser, (req, res) { (req.body.newtodo != ) { req.session.todolist.push(req.body.newtodo) } res.redirect( ) }) .get ( , (req, res) { (req.params.id != ) { req.session.todolist.splice(req.params.id, 1) } res.redirect( ) }) .use ( (req, res, next) { res.redirect( ) }) .listen(port, () => console.log(`MyTodo app is listening on port !`)) 'express' 'body-parser' 'cookie-session' false function '/todo' function 'todo.ejs' '/todo/add/' function if '' '/todo' '/todo/delete/:id' function if '' '/todo' function '/todo' ${port} Note that the above snippet is a derivative work of the code from the openclassroom.com website and explaining how this code works is beyond the scope of this tutorial. If the details are fuzzy, we recommend you check out to further your learning after you finish this tutorial. their site 3. Create a file called and paste into it the following content: ./views/todo.ejs <!DOCTYPE html> <html> <head> <title>My todolist</title> <style> a {text-decoration: none; color: black;} </style> </head> <body> <h1>My todolist</h1> <ul> <% todolist.forEach( (todo, index) { %> <li><a href= >✘</a> <%= todo %></li> <% }); %> </ul> <form action= method= > <p> <label = >What should I ?</label> <input = name= id= autofocus /> <input = /> </p> </form> </body> </html> function "/todo/delete/<%= index %>" "/todo/add/" "post" for "newtodo" do type "text" "newtodo" "newtodo" type "submit" 4. At this point, your directory structure should look something like the following: tree -L 2 -I node_modules . ├── app.js ├── package-lock.json ├── package.json └── views └── todo.ejs 1 directory, 4 files 5. Now you are ready to start your web server by entering: SECRET=bestkeptsecret; node app.js This will print out the following message to the console: MyTodo app is listening on port 3000! Create a Docker Image Now that you’ve written the Todo application, it's time to add create a Docker image for it. Each Docker container is based on a Docker image that contains all the information needed to deploy and run your app with Docker. To run a Docker container you can: Download an existing Docker image Create your own image In this tutorial, you'll create your own image. Note that a Docker image is usually comprised of multiple layers and each layer is basically a read-only filesystem. The way this works is that Docker creates a layer for each instruction found in the Dockerfile and places it atop of the previous layers. It is considered good practice to . place the application’s code, that changes often, closer to the bottom of the file 1. Create a file called and paste the following snippet into it: Dockerfile FROM node:10 WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD [ , ] "node" "app.js" Let’s take a closer look at this file: : sets the base image. Everything you’ll add later on it’ll be based on this image. In this example, we’re using Node.js version 10. FROM : this command sets the working directory that’ll be used for the COPY, RUN, and CMD commands. WORKDIR : this line of code runs the command inside your Docker container. RUN npm install : copies files from the build context into the Docker image COPY : specifies that a process running inside the container is listening to the 3000 port. This will be useful later in this tutorial when you’ll forward ports from the host to the container. EXPOSE : this line runs the inside your Docker container . CMD node app.js only after the container has been started 2. To avoid sending large files to the build context and speed up the process, you can use a file. This is nothing more than a plain text file that contains the name of the files and directories that should be excluded from the build. You can think of it as something similar to a file. Create a file called with the following content: .dockerignore .gitignore .dockerignore node_modules npm-debug.log 3. Now you can go ahead and build your Docker image by entering the command followed by: docker build The -t parameter which specifies the name of the image The path to the context which should point to the set of files you want to reference from your Dockerfile docker build -t prospectone/my-todo-list . Sending build context to Docker daemon 24.58kB Step 1/7 : FROM node:10 ---> c5d0d6dc0b5b Step 2/7 : WORKDIR /usr/src/app ---> Using cache ---> 508b797a892e Step 3/7 : COPY package*.json ./ ---> 0b821f725c19 Step 4/7 : RUN npm install ---> Running d692a6278d2b > ejs@3.0.1 postinstall /usr/src/app/node_modules/ejs > node ./postinstall.js Thank you installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/) npm WARN MyTodoApp@1.0.0 No description npm WARN MyTodoApp@1.0.0 No repository field. added 55 packages from 39 contributors and audited 166 packages 2.564s found 0 vulnerabilities Removing intermediate container d692a6278d2b ---> 067de030e269 Step 5/7 : COPY . . ---> 3141ccb6e094 Step 6/7 : EXPOSE 3000 ---> Running eb824e38d8c6 Removing intermediate container eb824e38d8c6 ---> b09d55adc1c4 Step 7/7 : CMD [ , ] ---> Running 7e77e0cbfa75 Removing intermediate container 7e77e0cbfa75 ---> c0a2db4c7a65 Successfully built c0a2db4c7a65 Successfully tagged prospectone/my-todo-list:latest in for in in "node" "app.js" in As mentioned above, the way the command works is that it adds a new layer for each command in your Dockerfile. Then, once a command is successfully executed, Docker deletes the intermediate container. docker build 4. Now that you’ve built your image, let’s run it by entering the command and passing it the following arguments: docker run with the port on the host (3001) that’ll be forwarded to the container (3000), separated by -p : to create an environment variable called and set its value to -e SECRET bestkeptsecret to specify that the container should be run in the background -d The name of the image ( ) prospectone/my-awesome-app docker run -p 3001:3000 -e SECRET=bestkeptsecret -d prospectone/my-todo-list db16ed662e8a3e0a93f226ab873199713936bd687a4546d2fce93e678d131243 5. You can verify that your Docker container is running with: docker ps The output should be similar to: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a6eb166191c7 prospectone/my-todo-list 4 seconds ago Up 3 seconds 0.0.0.0:3001->3000/tcp happy_hawking "docker-entrypoint.s…" 6. To inspect the logs, enter the command followed by the of your container: docker logs id docker logs a6eb166191c7 MyTodo app is listening on port 3000! 7. Now that your application is up and running, point your browser to and let us add a new todo. As you can see below, the application errors out on line 15 of the file: http://localhost:3001 todo.ejs In the next sections, you’ll learn how to debug this using Visual Studio Code. 8. But first, stop the container with: docker a6eb166191c7 kill a6eb166191c7 Enable Debugging in Microsoft Visual Studio Code Visual Studio Code provides debugging support for the Node.js applications running inside a Docker container. Follow the next steps to enable this feature: 1. Edit your Dockerfile by replacing the following line: CMD [ , ] "node" "app.js" with: CMD [ , , ] "npm" "run" "start-debug" Your Dockerfile should look something like the following: FROM node:10 WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD [ , , ] "npm" "run" "start-debug" 2. Open the file and add the following line to the object: package.json scripts : "start-debug" "node --inspect=0.0.0.0 app.js" This line of code starts the Node.js process and listens for a debugging client on port . 9229 Here’s how your file should look like: package.json { : , : , : , : , : { : , : }, : [], : , : , : { : , : , : , : } } "name" "MyTodoApp" "version" "1.0.0" "description" "" "main" "index.js" "scripts" "test" "echo \"Error: no test specified\" && exit 1" "start-debug" "node --inspect=0.0.0.0 app.js" "keywords" "author" "" "license" "ISC" "dependencies" "body-parser" "^1.19.0" "cookie-session" "^1.3.3" "ejs" "^3.0.1" "express" "^4.17.1" 3. Every time the Dockerfile gets updated, you must build again your Docker image: docker build -t prospectone/my-todo-list . Sending build context to Docker daemon 19.97kB Step 1/7 : FROM node:10 ---> c5d0d6dc0b5b Step 2/7 : WORKDIR /usr/src/app ---> Using cache ---> 508b797a892e Step 3/7 : COPY package*.json ./ ---> c0eec534b176 Step 4/7 : RUN npm install ---> Running a155901cb957 npm WARN MyAwesomeApp@1.0.0 No description npm WARN MyAwesomeApp@1.0.0 No repository field. added 50 packages from 37 contributors and audited 126 packages 11.504s found 0 vulnerabilities Removing intermediate container a155901cb957 ---> 010473a35e41 Step 5/7 : COPY . . ---> 76dfa12d4db4 Step 6/7 : EXPOSE 3000 ---> Running b5a334c9a2ea Removing intermediate container b5a334c9a2ea ---> b5a869ab5441 Step 7/7 : CMD [ , , ] ---> Running 1beb2ca9a391 Removing intermediate container 1beb2ca9a391 ---> 157b7d4cb77b Successfully built 157b7d4cb77b Successfully tagged prospectone/my-todo-list:latest in in in "npm" "run" "start-debug" in Note that the Step 7 has been updated, meaning that Docker will now execute the command. npm run start-debug 4. To enable debugging with Visual Studio Code, you must also forward port . Start your Docker container by entering: 9229 docker run -p 3001:3000 -p 9229:9229 -e SECRET=bestkeptsecret22222 -d perfops/my-todo-list 0f5860bebdb5c70538bcdd10ddc901411b37ea0c7d92283310700085b1b8ddc5 5. You can inspect the logs by entering the command followed the of your container: docker logs id docker logs 0f5860bebdb5c70538bcdd10ddc901411b37ea0c7d92283310700085b1b8ddc5 > My@1.0.0 start-debug /usr/src/app > node --inspect=0.0.0.0 app.js Debugger listening on ws://0.0.0.0:9229/59d4550c-fc0e-412e-870a-c02b4a6dcd0f For , see: https://nodejs.org/en/docs/inspector help Note that the debugger is now listening to port . Next, you’ll configure Visual Studio code to debug your application. 9229 Debug Your Application with Visual Studio Code 1. In Visual Studio Code, open the directory. MyTodoApp 2. The configuration for debugging is stored in a file called . To open it, press and then choose . launch.json Command+Shift+P Debug: Open launch.json 3. Replace the content of the file with the following snippet: launch.json { : , : [ { : , : , : , : 9229, : , : , : , : , : [ , ] } ] } "version" "0.2.0" "configurations" "name" "Docker: Attach to Node" "type" "node" "request" "attach" "port" "address" "localhost" "localRoot" " " ${workspaceFolder} "remoteRoot" "/usr/src/app" "protocol" "inspector" "skipFiles" " /node_modules/**/*.js" ${workspaceFolder} "<node_internals>/**/*.js" Note that we’re using the attribute to avoid stepping through the code in the directory and the built-in core modules of Node.js. skipFiles node_modules 4. Now everything is set up and you can start debugging your application. Remember that there was an error at line 15 in the file, which basically iterates over the array: . Looking at the file you’ll see that todo.ejs gets rendered at line 14. Let’s add a breakpoint so we can inspect the value of the variable: views.js todolist todolist.forEach(function(todo, index) app.js todolist 5. Enter to switch to the view. Then, click the button: Shift+Command+D Debug Debug and Run 6. To inspect the value of the variable, you must add a new expression to watch by selecting the sign and then typing the name of the variable ( ): req.session.todolist + req.session.todolist 7. Switch to the browser window and reload the page. http://localhost:3001 Note the message at the bottom. This means that our breakpoint has paused execution and we can inspect the value of the variable. Move back to Visual Studio to get details: Waiting for localhost req.session.todolist So the variable is . Can you think of how you could fix this bug? The answer is below, but don’t continue until you’ve given it some thought. req.session.todolist undefined 8. The template iterates over the array which should be stored in the current session. But we forgot to initialize this array so it’s . Let’s fix that by adding the following lines of code to the function : ejb todolist undefined .use (typeof (req.session.todolist) == ) { req.session.todolist = [] } if 'undefined' Make sure you paste this snippet just above the line of code that calls the next function. Your .use function should look like below: app.use(session({ secret: process.env.SECRET })) .use( (req, res, next) { (typeof (req.session.todolist) == ) { req.session.todolist = [] } next() }) function if 'undefined' 9. Retrieve the of your running container : id docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES cb9f175f7af3 prospectone/my-todo-list 15 minutes ago Up 15 minutes 0.0.0.0:9229->9229/tcp, 0.0.0.0:3001->3000/tcp nervous_hopper "docker-entrypoint.s…" 10. Stop the container by entering the command followed by its : docker kill id docker cb9f175f7af3 kill cb9f175f7af3 11. To apply the changes you must run the command again: docker build docker build -t prospectone/my-todo-list . Sending build context to Docker daemon 26.11kB Step 1/7 : FROM node:10 ---> c5d0d6dc0b5b Step 2/7 : WORKDIR /usr/src/app ---> Using cache ---> 508b797a892e Step 3/7 : COPY package*.json ./ ---> Using cache ---> c5ac875da76b Step 4/7 : RUN npm install ---> Using cache ---> 29e7b3bac403 Step 5/7 : COPY . . ---> b92f577afd57 Step 6/7 : EXPOSE 3000 ---> Running 78606a3c2e03 Removing intermediate container 78606a3c2e03 ---> 59c2ed552549 Step 7/7 : CMD [ , , ] ---> Running e0313973bb5a Removing intermediate container e0313973bb5a ---> 70a675646c0d Successfully built 70a675646c0d Successfully tagged prospectone/my-todo-list:latest in "npm" "run" "start-debug" in 12. Now you can run the container with: docker run -p 3001:3000 -p 9229:9229 -e SECRET=bestkeptsecret222212 -d prospectone/my-todo-list f75d4ef8b702df13749b10615f3945ea61b36571b0dc42b76f50b3c99e14f4c6 13. Inspect the logs by running the following command: docker logs 10f467dbb476 f75d4ef8b702df13749b10615f3945ea61b36571b0dc42b76f50b3c99e14f4c6 14. Reload the page and add a new task: Congratulations, you’ve successfully written a bare-bones todo app, ran it inside a Docker container, and used Visual Studio Code to debug it and fix a bug. In the next blog post, we’ll walk you through the process of dockerizing an existing application. About the author - Sudip is a Solution Architect with more than 15 years of working experience, and is the founder of . He likes sharing his knowledge through writing, and while he is not doing that, he must be fishing or playing chess. Javelynn . Previously posted at https://appfleet.com/