knowledge/technology/tools/Docker.md

105 lines
2.9 KiB
Markdown
Raw Normal View History

2023-12-04 10:02:23 +00:00
---
website: https://www.docker.com/
obj: application
---
#refactor
---
Notes:
- Docker (CLI)
- Dockerfile
- Docker Swarm
---
# Docker
[Docker](https://www.docker.com/) is a utility to pack, ship and run any application as a lightweight container. Another container engine is [Podman](Podman.md)
## Dockerfile
Every container can be build from a `Dockerfile`.
### Example
A sample `Dockerfile`:
```dockerfile
FROM node:12-alpine
RUN apk add --no-cache python2 g++ make
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]
EXPOSE 3000
```
`FROM` defines the base image the container builds upon.
`RUN` runs a specific command.
`WORKDIR` changes working directory.
`COPY` copies files into the container image.
`CMD` is run when the container starts.
`EXPOSE` exposes a port to the network.
`ENV` sets environment variables
`ENTRYPOINT` specifies the executable that will run when the container starts
`ARG` defines build-time variables that can be passed to the `docker build` command with the `--build-arg` flag
To build a `Dockerfile`:
```shell
docker build -t getting-started .
```
## Docker Compose
[Docker Compose](https://docs.docker.com/compose/) is an alternate CLI frontend for the Docker Engine, which specifies properties of containers using a `docker-compose.yml` YAML file rather than, for example, a script with `docker run` options. This is useful for setting up reoccuring services that are use often and/or have complex configurations.
### Example
```yaml
version: "3.7"
services:
app:
build: ./app
ports:
- 3000:3000
volumes:
- ./:/app
environment:
MYSQL_HOST: mysql
MYSQL_USER: root
MYSQL_PASSWORD: secret
MYSQL_DB: todos
mysql:
image: mysql:5.7
volumes:
- todo-mysql-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: todos
```
Every container is defined within the `services`.
Ports Forwards and Volumes are defined in their respective `ports` and `volumes`.
Everything inside `environment` is passed as a environment variable.
Containers can use a prebuild image (`image: image:tag`) or build one from scratch (`build: ./dir`)
### Usage
```shell
docker-compose -f docker-compose.yml up # Start services
docker-compose -f docker-compose.yml down # Stop services
docker-compose -f docker-compose.yml build # Rebuild services
docker-compose -f docker-compose.yml pull # Pull images
```
## Docker Swarm
Current versions of Docker include _swarm mode_ for natively managing a cluster of Docker Engines called a _swarm_. Use the Docker CLI to create a swarm, deploy application services to a swarm, and manage swarm behavior.
### Usage
```shell
# Create a swarm
docker swarm init --advertise-addr <MANAGER-IP>
# Get a join command on manager
docker swarm join-token worker
# Join a swarm
docker swarm join --token <TOKEN> <MANAGER-IP>:2377
# View node info
docker node ls
```