Python the programming language of the future.
May 20, 2021Explaining filter array method map array method and reduce array method in javascript
May 20, 2021Welcome to Metric Tree Labs blog series and in today’s blog, we will be walking you through the basics of docker and how to deploy a node.js app on docker.
WHAT is Docker.
Docker is a service that uses OS-level virtualization to deliver software in packages called containers. Compared to virtual machines that run host operating systems, docker doesn’t need a hypervisor, all it needs is an OS that supports programs, libraries and system resources to run a specific program. And it can run a lot more applications at the same time than what would be possible with a virtual machine.
Installation
- https://docs.docker.com/install/ link to download and install docker.
- Docker –version and docker info to get version and detailed information about your docker installation.
- Run docker run hello-world to test the installation.
Node App
- We have a simple node.js server (app.js) running on port 3000.
- The server exposes a route “/” that responds with a message saying whether the server is running inside a container or not by looking up the environment variable IN_CONTAINER.
- You can start the server by running npm start.
- Visit localhost:3000 on your browser after starting the server.
Dockerfile
- To deploy our server on docker we start by creating a file named Dockerfile.
- Contents of Dockerfile
- FROM: The FROM instruction initializes a new build stage and sets the Base Image for subsequent instructions.
- WORKDIR: Sets the current working directory for subsequent commands and instructions
- COPY: copies new files or directories from <src> and adds them to the filesystem of the container at the path
- RUN: To run commands
- ENV: Sets the environment variable
- CMD: Default command to execute. A Dockerfile can have only one CMD instruction
- We also create a dockerignore file that ignores specified files and folders when copying from our directory to the container.
Creating a Docker image
- To build the docker image run docker build –tag=<name>.
- We can list the images using docker image ls command
Running Containers
- Use the command docker run -p 3000:3000 <image-name> ( -p flag exposes and connects the port 3000 on the container to the system’s port )
- Visit localhost:3000 in your browser and It should now display the message server running inside a container.
- To stop the container press Ctrl+c. Containers can be run in the background using the detached mode by adding the flag -d.
- To view, a list of running containers run docker container ls
- Stop a container by running docker container stop <container-id>
Deleting Images
- Run docker image rm <image-id>
- Run docker image rm <image-id>