You might’ve heard about Docker. It might’ve sounded interested, but you didn’t know why you would use it, or it appeared scary. No fear, it’s actually quite straight-forward.
Firstly, you’ll need to download Docker itself. This is an application you will install and run like any other application. You even get a nice icon in your dock! :) You can even install this using Brew.
brew cask install docker
Docker is a way of defining a set of software for your application. This stops the whole “it works on my machine” that developers love to proclaim.
The main part of Docker is a
Dockerfile. This contains the definition of your server and what you want to install.
Dockerfile contains instructions which should be run when the container starts.
A common starting point is to use a Docker image from the official repository
FROM node:12.11.1-alpine AS your_app # Create app directory. WORKDIR /usr/app/ # Copy package information and src files. COPY package.json package-lock.json ./ COPY src ./src # Install the packages needed for production. RUN npm install --only=production # Build the source. RUN npm run build # Remove the src. RUN rm -rf ./src EXPOSE 9000 CMD [ "npm", "start" ]
You can start your containers using the command line. This is OK with a simple set of instructions.
A better solution is to define them using
version: "3.7" services: app: build: context: . dockerfile: Dockerfile image: your_app:latest container_name: your_app ports: - "9001:9000"
This will build your container using the
Dockerfile you have created. It will use the files in the current
directory using the
context. It will also name your container so you can access it easily. Finally, it exposes
port 9001 on your machine to port 9000 in the container.
Finally, you can run everything using the following command;
docker-compose -f ./docker-compose.yaml up -d --build
This will start up your Docker containers using the
docker-composer.yaml file. It will also
the container from scratch, in case you already have an older version. Without the
--build flag, it
will use an existing build if one exists.
If you want to see what containers you have built and their status, you can run the following;
docker ps -a
To list all the images you have created or used;
If you want to get shell access to your container, then you would do the following;
docker exec -it your_app sh
Sometimes you want to cleanup the containers and images you have created. Below are a few commands which'll help with that.
docker stop your_app -t 0 # Stop your app. docker rm your_app # Remove your app container. docker rmi your_app # Remove your app image.