Docker Compose


Docker Compose

두개의 컨테이너를 연결하는 것 --link를 통해

ip 몰라도 가능

ex) maria DB와 apache 컨테이너를 연결 하기

 

1. 명령어 기반

더보기
# mydb run
[vagrant@dcentos ~]$ docker run -d --name=mydb -p 9001:3306 --env MYSQL_ROOT_PASSWORD=mypass --env MYSQL_USER=myuser --env MYSQL_PASSWORD=userpass --env MYSQL_DATABASE=mydb -v /var/dbdata:/var/lib/mysql mysql:5.5
Unable to find image 'mysql:5.5' locally
5.5: Pulling from library/mysql
743f2d6c1f65: Pull complete
3f0c413ee255: Pull complete
aef1ef8f1aac: Pull complete
f9ee573e34cb: Pull complete
3f237e01f153: Pull complete
03da1e065b16: Pull complete
04087a801070: Pull complete
7efd5395ab31: Pull complete
1b5cc03aaac8: Pull complete
2b7adaec9998: Pull complete
385b8f96a9ba: Pull complete
Digest: sha256:12da85ab88aedfdf39455872fb044f607c32fdc233cd59f1d26769fbf439b045
Status: Downloaded newer image for mysql:5.5
db875551466f08294e8bb4eadb7f446350a592d69dd087024e5ea7116b03230c

# myapache run link로 연결
[vagrant@dcentos ~]$ docker run -d --name myapache -p 9000:80 --link mydb:mysql5 httpd:2.4
Unable to find image 'httpd:2.4' locally
2.4: Pulling from library/httpd
Digest: sha256:104f07de17ee186c8f37b9f561e04fbfe4cf080d78c6e5f3802fd08fd118c3da
Status: Downloaded newer image for httpd:2.4
7ff94a99a90c1184403120f7ba058d12aff44d7972ffa617c1cbf0403222e187

# 상태 확인
[vagrant@dcentos ~]$ docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                                       NAMES
7ff94a99a90c   httpd:2.4   "httpd-foreground"       5 seconds ago    Up 4 seconds    0.0.0.0:9000->80/tcp, :::9000->80/tcp       myapache
db875551466f   mysql:5.5   "docker-entrypoint.s…"   46 seconds ago   Up 45 seconds   0.0.0.0:9001->3306/tcp, :::9001->3306/tcp   mydb

# 링크를 사용하면 /etc/hosts파일에 추가됨 (즉 ip몰라도 된다.)
[vagrant@dcentos ~]$ docker exec -it myapache cat /etc/hosts
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2      mysql5 db875551466f mydb
172.17.0.3      7ff94a99a90c

명령어가 상당히 복잡하다. 그러니까 yaml파일을 만들자

 

2. yaml 파일로 작성

[vagrant@dcentos work]$ cat docker_compose_sample.yaml
version: '3.9' # docker compose version
services:
  myapache: # container name
    image: httpd # docker image name:tag
    ports: # port forwarding
    - "9000:80"
  mydb:
    image: mysql
    ports:
    - "9001:3306"
    environment:
    - MYSQL_ROOT_PASSWORD=mypass
    - MYSQL_USER=myuser
    - MYSQL_PASSWORD=userpass
    - MYSQL_DATABASE=mydb
    volumes: # mount
    - /var/dbdata:/var/lib/mysql

 

실행

docker compse -f [파일명] up

백그라운드로 실행하고자 한다면 up 뒤에 -d 붙이기

더보기
[vagrant@dcentos work]$ docker compose -f docker_compose_sample.yaml up
[+] Running 2/0
 ✔ Container work-mydb-1      Created                                                         0.1s
 ✔ Container work-myapache-1  Created                                                         0.1s
Attaching to myapache-1, mydb-1
myapache-1  | AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.18.0.2. Set the 'ServerName' directive globally to suppress this message
myapache-1  | AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.18.0.2. Set the 'ServerName' directive globally to suppress this message
myapache-1  | [Wed Mar 06 04:16:24.466750 2024] [mpm_event:notice] [pid 1:tid 140490193778560] AH00489: Apache/2.4.58 (Unix) configured -- resuming normal operations
myapache-1  | [Wed Mar 06 04:16:24.466989 2024] [core:notice] [pid 1:tid 140490193778560] AH00094: Command line: 'httpd -D FOREGROUND'
mydb-1      | 2024-03-06 04:16:24+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.3.0-1.el8 started.
mydb-1      | 2024-03-06 04:16:24+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
mydb-1      | 2024-03-06 04:16:24+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.3.0-1.el8 started.
mydb-1      | '/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'
mydb-1      | 2024-03-06T04:16:25.252662Z 0 [System] [MY-015015] [Server] MySQL Server - start.
mydb-1      | 2024-03-06T04:16:25.473516Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.3.0) starting as process 1
mydb-1      | 2024-03-06T04:16:25.492949Z 1 [System] [MY-011012] [Server] Starting upgrade of data directory.
mydb-1      | 2024-03-06T04:16:25.493006Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
mydb-1      | 2024-03-06T04:16:25.578801Z 1 [ERROR] [MY-013090] [InnoDB] Unsupported redo log format (v0). The redo log was created before MySQL 5.7.9
mydb-1      | 2024-03-06T04:16:25.578852Z 1 [ERROR] [MY-012930] [InnoDB] Plugin initialization aborted with error Generic error.
mydb-1      | 2024-03-06T04:16:26.058404Z 1 [ERROR] [MY-011013] [Server] Failed to initialize DD Storage Engine.
mydb-1      | 2024-03-06T04:16:26.059436Z 0 [ERROR] [MY-010020] [Server] Data Dictionary initialization failed.
mydb-1      | 2024-03-06T04:16:26.059458Z 0 [ERROR] [MY-010119] [Server] Aborting
mydb-1      | 2024-03-06T04:16:26.061879Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.3.0)  MySQL Community Server - GPL.
mydb-1      | 2024-03-06T04:16:26.061909Z 0 [System] [MY-015016] [Server] MySQL Server - end.
mydb-1 exited with code 1

응용

apache와 mysql 연동시키면서 DB에 볼륨 마운트 시키기

depends_on: << 이건 아래에 있는 녀석 먼저 실행하고 나중에 실행 하라는 것임

더보기
[vagrant@dcentos work]$ cat compose_sample.yaml
version: '3.9'
networks:
  webapps:
    driver: bridge
    ipam:
      config:
      - subnet: 172.30.0.0/16
services:
  myapche:
    image: httpd:2.4
    ports:
    - "9000:80"
    networks:
      webapps:
        ipv4_address: 172.30.0.10

 #   links:  (deprecated)
 #     - mydb:db
    depends_on:
    - mydb
  mydb:
    image: mysql:5.7
    ports:
    - "9001:3306"
    networks:
      webapps:
        ipv4_address: 172.30.0.11
    environment:
    - MYSQL_ROOT_PASSWORD=mypass
    - MYSQL_USER=user1
    - MYSQL_PASSWORD=userpass
    - MYSQL_DATABASE=userdb
    volumes:
    - dbfiles:/var/lib/mysql
volumes:
  dbfiles:

Todolist 예제

파일과 실행 결과만 적음

더보기
[vagrant@dcentos web_apps]$ tree
.
├── docker
│   ├── mysql
│   │   ├── Dockerfile
│   │   └── todo.sql
│   └── php
│       └── Dockerfile
├── docker-compose.yml
├── html
│   ├── index.php
│   └── style.css
└── logs


[vagrant@dcentos web_apps]$ cat docker-compose.yml
version: '3.9'

networks:
  webapps:

services:
  php:
    build: ./docker/php
    volumes:
      - ./html:/var/www/html
      - ./logs:/var/log/apache2/
    ports:
      - '8000:80'
    networks:
      webapps:
    depends_on:
      - db
    container_name: myphp
  db:
    build: ./docker/mysql
    networks:
      webapps:
    container_name: mydb

[vagrant@dcentos web_apps]$ cat docker/mysql/Dockerfile
FROM mysql:5.7
ENV MYSQL_ROOT_PASSWORD=mypass MYSQL_DATABASE=todo
ADD ./todo.sql /docker-entrypoint-initdb.d/
EXPOSE 3306

[vagrant@dcentos web_apps]$ cat docker/mysql/todo.sql
USE todo;
CREATE TABLE tasks (
        id int not null auto_increment,
        task varchar(255),
        primary  key(id)
);

[vagrant@dcentos web_apps]$ cat docker/php/Dockerfile
FROM centos:7
RUN yum -y install httpd
RUN yum -y install php php-mysql
EXPOSE 80
ENTRYPOINT ["httpd","-D","FOREGROUND"]

[vagrant@dcentos web_apps]$ cat html/index.php
<?php
    // initialize errors variable
        $errors = "";

        // connect to database
        $db = mysqli_connect("mydb", "root", "mypass", "todo");

        // insert a quote if submit button is clicked
        if (isset($_POST['submit'])) {
                if (empty($_POST['task'])) {
                        $errors = "You must fill in the task";
        }else{
                        $task = $_POST['task'];
                        $sql = "INSERT INTO tasks (task) VALUES ('$task')";
                        mysqli_query($db, $sql);
                        header('location: index.php');
                }
        }

        // delete task
        if (isset($_GET['del_task'])) {
                $id = $_GET['del_task'];

                mysqli_query($db, "DELETE FROM tasks WHERE id=".$id);
                header('location: index.php');
        }
?>
<!DOCTYPE html>
<html>
<head>
        <title>ToDo List Application PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
        <div class="heading">
                <h2 style="font-style: 'Hervetica';">ToDo List Application PHP and MySQL database</h2>
        </div>
        <form method="post" action="index.php" class="input_form">
                <input type="text" name="task" class="task_input">
                <button type="submit" name="submit" id="add_btn" class="add_btn">Add Task</button>
        <?php if (isset($errors)) { ?>
        <p><?php echo $errors; ?></p>
<?php } ?>
        </form>
        <table>
        <thead>
                <tr>
                        <th>N</th>
                        <th>Tasks</th>
                        <th style="width: 60px;">Action</th>
                </tr>
        </thead>

        <tbody>
                <?php
                // select all tasks if page is visited or refreshed
                $tasks = mysqli_query($db, "SELECT * FROM tasks");

                $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
                        <tr>
                                <td> <?php echo $i; ?> </td>
                                <td class="task"> <?php echo $row['task']; ?> </td>
                                <td class="delete">
                                        <a href="index.php?del_task=<?php echo $row['id'] ?>">x</a>
                                </td>
                        </tr>
                <?php $i++; } ?>
        </tbody>
</table>
</body>
</html>

[vagrant@dcentos web_apps]$ cat html/style.css
.heading{
        width: 50%;
        margin: 30px auto;
        text-align: center;
        color:  #6B8E23;
        background: #FFF8DC;
        border: 2px solid #6B8E23;
        border-radius: 20px;
}
form {
        width: 50%;
        margin: 30px auto;
        border-radius: 5px;
        padding: 10px;
        background: #FFF8DC;
        border: 1px solid #6B8E23;
}
form p {
        color: red;
        margin: 0px;
}
.task_input {
        width: 75%;
        height: 15px;
        padding: 10px;
        border: 2px solid #6B8E23;
}
.add_btn {
        height: 39px;
        background: #FFF8DC;
        color:  #6B8E23;
        border: 2px solid #6B8E23;
        border-radius: 5px;
        padding: 5px 20px;
}

table {
    width: 50%;
    margin: 30px auto;
    border-collapse: collapse;
}

tr {
        border-bottom: 1px solid #cbcbcb;
}

th {
        font-size: 19px;
        color: #6B8E23;
}

th, td{
        border: none;
    height: 30px;
    padding: 2px;
}

tr:hover {
        background: #E9E9E9;
}

.task {
        text-align: left;
}

.delete{
        text-align: center;
}
.delete a{
        color: white;
        background: #a52a2a;
        padding: 1px 6px;
        border-radius: 3px;
        text-decoration: none;
}​

 

[vagrant@dcentos web_apps]$ docker compose -f docker-compose.yml up -d
[+] Building 38.2s (14/14) FINISHED                                                 docker:default
 => [db internal] load build definition from Dockerfile                                       0.0s
 => => transferring dockerfile: 218B                                                          0.0s
 => [db internal] load metadata for docker.io/library/mysql:5.7                               0.0s
 => [db internal] load .dockerignore                                                          0.0s
 => => transferring context: 2B                                                               0.0s
 => [db internal] load build context                                                          0.0s
 => => transferring context: 200B                                                             0.0s
 => [db 1/2] FROM docker.io/library/mysql:5.7                                                 0.1s
 => [db 2/2] ADD ./todo.sql /docker-entrypoint-initdb.d/                                      0.0s
 => [db] exporting to image                                                                   0.0s
 => => exporting layers                                                                       0.0s
 => => writing image sha256:c9f14501d6cfa6797c8e2ef73d46739dc6f576e360b84739ce95b322583917de  0.0s
 => => naming to docker.io/library/web_apps-db                                                0.0s
 => [php internal] load build definition from Dockerfile                                      0.0s
 => => transferring dockerfile: 217B                                                          0.0s
 => [php internal] load metadata for docker.io/library/centos:7                               0.0s
 => [php internal] load .dockerignore                                                         0.0s
 => => transferring context: 2B                                                               0.0s
 => CACHED [php 1/3] FROM docker.io/library/centos:7                                          0.0s
 => [php 2/3] RUN yum -y install httpd                                                       30.7s
 => [php 3/3] RUN yum -y install php php-mysql                                                5.1s
 => [php] exporting to image                                                                  1.9s
 => => exporting layers                                                                       1.9s
 => => writing image sha256:ac0d3b342a66710d256d000fd65522abb947bf8979dedacecbe2d2507e83b8a3  0.0s
 => => naming to docker.io/library/web_apps-php                                               0.0s
[+] Running 2/3
 ⠋ Network web_apps_webapps  Created                                                          1.0s
 ✔ Container mydb            Started                                                          0.5s
 ✔ Container myphp           Started                                                          0.9s​
완료. 아따 깔끔하네

나중에 해볼거

Docker compose를 활용해서 mysql과 wordpress를 연동시켜보자

내가 만들었던 php todolist를 컨테이너화 시켜보자

 

'Container > Docker' 카테고리의 다른 글

Docker Swarm  (0) 2024.03.06
Docker Hub에 업로드하기  (0) 2024.03.06
Dockerfile 명령어, Multi-stage build  (0) 2024.03.05
Container image  (0) 2024.03.05
Docker Network  (0) 2024.03.04

+ Recent posts