---
# System prepended metadata

title: Container Cooperation
tags: [docker, Linux]

---

# Container Cooperation

* Container1: Apache + php
* Container2: Mysql
![photo_2024-04-24_10-04-44](https://hackmd.io/_uploads/HkB1YkUZR.jpg)

## step by step

### images install

* install
```bash=
$ sudo docker pull mysql
$ sudo docker pull radys/php-apache:7.4
```
```bash=
$ sudo docker images
REPOSITORY                    TAG              IMAGE ID       CREATED        SIZE
mysql                         latest           a3b6608898d6   4 weeks ago    596MB
radys/php-apache              7.4              51289344b921   2 years ago    422MB
```

### mysql
* sql set
```bash=
# 先建立映射的目錄
$ mkdir -p dbtest
$ pwd
/home/user/docker_php/dbtest
```
* run
```bash=
$ sudo docker run -d --network test-network --name hello-mysql -e MYSQL_ROOT_PASSWORD=123456 -v /home/user/docker_php/dbtest/:/var/lib/mysql mysql:3.0
8a98edbc2f656cd9da25dd2b5609096b7302d325be67614a994b038384779c77
[user@docker1 ~]$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                                                    NAMES
8a98edbc2f65   mysql     "docker-entrypoint.s…"   6 seconds ago   Up 5 seconds   33060/tcp, 0.0.0.0:32768->3306/tcp, :::32768->3306/tcp   hello-mysql
```

:::info
1. 網路建立: [Network Create](https://hackmd.io/b0ReOSeyS4WC5wubgCBZnQ#:~:text=address%20%27b3%27-,%E8%87%AA%E8%A8%82%20bridge%20network,-%E7%95%99%E8%A8%80)
2. "-p 3306" 不像以往 "-p 8080:80", 只要給內部互通而已, 沒有要對外, 所以 port 就不細設, 隨機分配

![image](https://hackmd.io/_uploads/BkKRTibHT.png)
:::

```bash=
# 進入Container
$ sudo docker exec -it hello-mysql bash
bash-4.4#
# 透過 root 進入 mysql (密碼在建立container時設定)
bash-4.4# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.2.0 MySQL Community Server - GPL

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
```
* 資料庫簡易設定
```sql=
mysql> create database testdb;
Query OK, 1 row affected (0.01 sec)

mysql> use testdb;
Database changed

mysql> create table addrbook(name varchar(50) not null, phone varchar(100));
Query OK, 0 rows affected (0.03 sec)

mysql> insert into addrbook(name, phone) values ("Tom", "0912345678");
Query OK, 1 row affected (0.03 sec)

mysql> insert into addrbook(name, phone) values ("Marry", "0987654321");
Query OK, 1 row affected (0.00 sec)

mysql> select * from addrbook;
+-------+------------+
| name  | phone      |
+-------+------------+
| Tom   | 0912345678 |
| Marry | 0987654321 |
+-------+------------+
2 rows in set (0.00 sec)
```
**這邊退出DB之後把container 儲存一份**
```bash=
$ sudo docker commit hello-mysql mysql:3.0
sha256:36bd9990c9d6ff0ae8d06e813b1f8aa395851924d4ffefa53433d5f5ddaccf34
```

### Apache + php
* run
```bash=
$ sudo docker run -d -p 80:80 --network test-network -v /home/user/docker_php/:/var/www/html --name hello-php radys/php-apache:7.4
2612686c5dec1a085709d79bdcf5141cf74db1fa4d389e402c117bb40171d983
```
* edit php (test)
```php=
<?php
phpinfo();
?>
```
![image](https://hackmd.io/_uploads/SkVdBhZSa.png)

* edit index.php
```php=
<?php
$servername="hello-mysql";
$username="root";
$password="123456";
$dbname="testdb";

$conn = new mysqli($servername, $username, $password, $dbname);

if($conn->connect_error){
  die("connection failed:" . $conn->connect_error);
}

$sql="select name, phone from addrbook";
$result = $conn->query($sql);

if($result->num_rows >0){
  while($row = $result->fetch_assoc()){
    echo "name:" . $row["name"]." phone:".$row["phone"]."<br>";
  }
} else {
  echo "0 result";
}

?>
```
![image](https://hackmd.io/_uploads/Sy1q8hbS6.png)

## docker-compose LAMP
### docker-compose (有瑕疵版, 必須利用前面commit的image)
```dockerfile=
version: '3.8'
services:
  hello-php:
    image: radys/php-apache:7.4
    container_name: hello-php
    depends_on:
    - hello-mysql
    ports:
    - "80:80"
    volumes:
    - /home/user/docker_php/:/var/www/html/
    networks:
    - test-network
  hello-mysql:
    image: mysql:3.0
    container_name: hello-mysql
    environment:
      MYSQL_ROOT_PASSWORD: 123456
    ports:
      - "3306"
    volumes:
      - /home/user/docker_php/dbtest/:/var/lib/mysql
    networks:
      - test-network
networks:
  test-network:
```

### docker-compose

* 先把剛剛映射的目錄清空(或建立新的)
```bash=
[user@docker1 dbtest]$ sudo rm -rf *
```
* 測試的目錄裡要有
```bash=
[user@docker1 docker_php]$ ls
dbtest(目錄)  docker-compose.yml  dump(目錄)  index.php
```
* 編輯 yml 檔
```dockerfile=
version: '3.8'
services:
  hello-php:
    image: radys/php-apache:7.4
    container_name: hello-php
    depends_on:
    - hello-mysql
    ports:
    - "80:80"
    volumes:
    - /home/user/docker_php/:/var/www/html/
    networks:
    - test-network
  hello-mysql:
    image: mysql
    container_name: hello-mysql
    environment:
      MYSQL_ROOT_PASSWORD: 123456
      MYSQL_DATABASE: testdb    # 這個是建立名為 testdb 的資料庫
    ports:
      - "3306"
    volumes:
      - /home/user/docker_php/dbtest/:/var/lib/mysql
      - ./dump:/docker-entrypoint-initdb.d    # 映射 dump 目錄上去
    networks:
      - test-network
networks:
  test-network:
```
* 目錄 dump
```bash=
[user@docker1 dump]$ ls
dump.sql
```
* dump.sql
```sql=
use testdb;
create table addrbook(name varchar(50) not null, phone varchar(100));
insert into addrbook(name, phone) values ("Tom", "0912345678");
insert into addrbook(name, phone) values ("Marry", "0987654321");
```
* run
```bash=
$ sudo docker-compose up -d
[+] Running 3/3
 ✔ Network docker_php_test-network  Created                      0.1s 
 ✔ Container hello-mysql            Started                      0.0s 
 ✔ Container hello-php              Started                      0.0s 
```

## docker-compose flask+redis

**計算連線次數**

* directory
```bash=
[user@d1 test6]$ ls
app.py  docker-compose.yaml  Dockerfile  requirements.txt
```
* app.py
```python=
from flask import Flask
import time
import redis

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
  retries = 5
  while True:
    try:
      return cache.incr('hits')
    except redis.exceptions.ConnectionError as exc:
      if retries == 0:
        raise exc
    retries -= 1
    time.sleep(0.5)


@app.route('/')
def get_index():
  count = get_hit_count()
  return 'HAHA, Already browse {} time.'.format(count)

app.run(host='0.0.0.0', debug=True)
```
* Dockerfile
```dockerfile=
[user@d1 test6]$ cat Dockerfile 
FROM python:3.9
ADD ./ /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
```
* requirements.txt
```=
flask
redis
```
* docker-compose.yaml
```dockerfile=
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - ./:/code/
    depends_on:
      - redis
  redis:
    image: "redis:alpine"
```

* result
![image](https://hackmd.io/_uploads/Bk5cFd_M0.png)
