Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this final stage, we'll take everything we've learned so far and Dockerize a simple Node.js web app.
This Node.js web app simply listens for connections on port 80, and responds with the message "Hello from Node.js!".
server.js
'use strict';
const express = require('express');
// Constants
const PORT = 80;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Node.js!\n');
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
Like most Node apps, this app also includes a file named package.json
that defines how it's built. The "start"
line is particularly important; it contains the command that will run the server.
package.json
{
"name": "docker_web_app",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "Jared Smith <jared@jaredthecoder.com>",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.13.3"
}
}
Now that we have our server code, it's time to build the Dockerfile to deploy it!
# Build off this base image
FROM node:7
# Set up app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
# Expose the server to the host machine
EXPOSE 8080
# Run this command on startup
ENTRYPOINT ["npm", "start"]
New Terms
- Node.js: A JavaScript runtime for non-browser environments.
- package.json: A file that defines a JavaScript packages settings (i.e. how to build it, how to start it, metadata, etc.)
- Express: A JavaScript/Node.js web server framework, like Flask or Django for Python, or Sinatra or Ruby on Rails for Ruby.
- NPM: Node.js Package Manager, the package manager for installing JavaScript/Node.js packages into your development or production environment.
Further Reading
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up