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.
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.
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.
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.
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.
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.
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.
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."
After executing, we can now see that our container is running. Let's verify this by opening a browser window and typing "localhost:8000."