Build a Simple Node.js Web Server with Docker

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

Learn how to build a simple Node.js web server with Docker. In this lesson, we'll create a Dockerfile for a simple Node.js script, copy and build it into a Docker image, and start a container to run the web server.

[00:00] Let's create a simple Docker image of a Node.js webserver. Here's a simple script that will respond, "Hello World" on every request. Note that the server is listening on port 8000. We'll need to know this, and expose the port in the Docker image, and later map it to our host.

[00:14] Create a new file called "Docker file." A Docker file is a text document which provides the Docker engine with instructions on how to build the image. Every Docker file starts with the "from" keyword, followed by the name of our base image.

[00:26] A base image is another Docker image from which we'll build our image. Since we're running a Node web server, we'll use the mhart/alpine-node image as our base. The following line is "copy index.js." which will copy our index.js file into our image.

[00:42] You can use the "copy" keyword to copy any files to your Docker image. By default, you can think of Docker as having a firewall with no ports opened. Since we're running a web server, we'll need to open up the port the server is running on.

[00:55] Let's add "expose 8000" to our Docker file. The last line in every Docker file is typically the "cmd" or "command" keyword, followed by our executable. We'll use a simple command to start our web server, "Node index.js." This is now a valid Docker file.

[01:11] Next, we'll use it to build our Docker image. From our project directory, run "Docker build -t myserver." The "-t" specifies the name of our Docker image. The trailing dot tells Docker which directory to look for our Docker file.

[01:26] After executing it, you can verify the image was built by running "Docker images." We can test it by running "Docker run." We'll also specify a "-p" flag, which maps a host port to a container port.

[01:39] You can think of this as port forwarding through a firewall. Let's map port 8000 on our host to port 8000 on our container. Lastly, we'll add the name of our Docker image we specified when we built our image, "myserver."

[01:52] After executing, we can now see that our container is running. Let's verify this by opening a browser window and typing "localhost:8000."