What is docker and why should you use it?
Docker is a platform as a service which allows you to isolate an entire operating system via Linux containers. The files we create below are instructions for how Docker should build the Linux container. Dockerizing (is that a word?) your application should be the first step in your workflow as it provides a good base for your development and production environments. Onboarding new members to the project is easy too, just provide them the respective Dockerfile and they’re good to go. Docker can become extremely complicated and you can add a lot of configuration to your application with Docker alone.
You will definitely benefit from spending time researching complex features of Docker!
Add docker to your NodeJS app in 4 steps
I don’t explain what the following code does, but docker has great documentation on it, https://docs.docker.com/engine/reference/builder/ .
All of the following config files will be at the root of your project. These files will work for probably 90% of your NodeJS applications, barring specific configuration.
If this is an application that will be shipped to production, create a separate Dockerfile.prod that contains configuration for your production application. These config settings can be googled because there are many people who have used Docker in production. This helps separate dev vs prod configuration with ease.
- Create a
Dockerfile.devwith the following code:
- Create a
docker-compose.ymlwith the following code:
- Create a
.dockerignoreand addnode_modulesto it. Any files/folders in the.dockerignorewill not be copied over to the Docker container. Sincenode_modulesis usually a large directory, adding this to a.dockerignorethis will speed up your build times. Add other files/directories you do not want to be copied into your docker container here!
- Execute the following commands in the root directory of your project depending on what you need:
docker-compose up -d --build: Builds the container using Dockerfile.dev and starts your docker container in detached modedocker-compose up -dStarts your docker container in detached modedocker-compose downALWAYS run this command when stopping your containerdocker psLists your current active containers
After the initial build is successful execute docker ps and ensure that your container is running. If so, head on over to localhost:5000 where your application is hosted locally. You can change this port through the port setting in the docker-compose.yml .
Top comments (3)
hummm... what about environment variables? Can you tell me some tips about handle environment vars?
Yup I can do that! You can save environment variables directly into a Dockerfile using the "ENV" key OR create a .env file in your root directory and access environment variables it in your application with "process.env.ENV_VARIABLE".
docs.docker.com/compose/environmen...