Docker Basics
What is Docker and what is it used for?
Docker is a containerization tool that allows your code to run exactly the same way, no matter what environment you run it in. It allows you to port your app to different environments (i.e. computers/servers/cloud providers) and you can be confident that it will always run and work the same way.
Dockerfile - What is it?
A Dockerfile is essentially a configuration file to use with Docker. You create a Dockerfile in your project and can then build that Dockerfile into what Docker calls an image. There are tons of configuration options for Dockerfiles, but what you basically need to understand is that this Dockerfile just serves as a configuration file for running containers within Docker.
What does a sample Dockerfile look like?
FROM node
WORKDIR /app
COPY package.json.
RUN npm install
COPY ..
EXPOSE 80
CMD ["node", "app.js"]
I won’t go into the nitty gritty details of this Dockerfile since this is just a high level overview, but each of these lines are Docker specific instructions on how you want things to work within your image.
The basics of Docker images
You can almost think of Docker images as a blueprint to how you want things to work.
What are Docker containers?
Docker containers are simply the running version of the Docker images that you have created. Your Docker image is a blueprint for how you want things to work, and the container runs that blueprint.
Useful commands
docker build -t
This takes a Dockerfile and builds an image from it. Once that image is built, you can then run a container based on that image.
The command above specifically
- Builds an image using the Dockerfile in the directory you run the command in
- Assigns that image a “tag” (i.e. name) that you can reference with future Docker commands
docker run —name
Docker run essentially runs a container based on a specific image. You can add multiple options to this command to run the container in specific ways
- -d: Detached mode, allowing you to run it in the background so you can continue using the terminal
- -p: Just publishes the port you want to use
- —rm: This will remove the container once you stop it
docker network create
Test mongo username/password within interactive terminal
// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash
// Enter into mongo shell
$ mongo
// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("username-goes-here", passwordPrompt())
// Show available databases
$> show dbs
.dockerignore
node_modules
Dockerfile
.git