Docker in 30 mins

Docker in 30 mins with a Node.JS application

To start using Docker for your application(s), you will need Docker installed on your machine, a node.js you wish to containerise with Docker, and optionally a Docker Hub account to host your docker image.

Prerequisites

Install docker. A list of the supported platforms and instructions for installing docker on those platforms are located here.

Before you continue, ensure you can run the docker hello-world example by running docker run hello-world in a terminal. You should see an output like the below:

hello-world-output

Containerising your app

Dockerfile

To containerise your app you will need a Dockerfile for your app. Create a file named ‘Dockerfile’ in the root of your app directory with the following content:

FROM node:6.10.2-alpine

\# Create app directory  
RUN mkdir -p /usr/src/app  
WORKDIR /usr/src/app  

\# Install app dependencies  
COPY package.json /usr/src/app/  
RUN npm install  

\# Bundle app source  
COPY . /usr/src/app  

EXPOSE 8000  

CMD [ "npm", "start" ] # make sure start script in package.json

** the above presumes your app listens on port 8000, and that you have a start script in your package.json:

"scripts": {  
    "start": "node app.js"  
},

Build your app docker container

Run the following from the root of your app directory:

Or if you wish to tag the image with your username:

If you have any errors regarding the location of your DockerFile, you may need to specify the path to your DockerFile:

You should see an output like the following:

build-output

Run your container app

Once your docker container is built run it with:

Sample output should resemble:

running-your-container

** the above presumes 8000 is the port number your nodejs app runs on, and that you wish to map it to port 49160 on your local machine.

If you have been successful, you will now be able to access your app through port 49160 - congratulations, you have just built and run your first containerised app!

Check your containers

To return a list of all running docker containers (and retrieve the id of your container):

docker-ps-output

Checking your container logs

To check the logs from your container run:

docker-logs-output

Getting inside your container

To access a bash terminal within the container run:

Stopping your docker container

To stop a docker container run:

To delete a docker container image once stopped run:

(Optional) Docker Hub

To host your container images on Docker Hub, ensure you have an account, then:

dockerhub-login

Troubleshooting tips

If you encounter any errors the docker error messages are generally helpful enough to diagnose and resolve the issue. Some issues that were encountered included: