# Practical examples

## Python external program using docker MySQL

### Create MySQL container

In this example, we'll work with user **root.**

* <https://hub.docker.com/_/mysql>

#### Create container with config

```bash
docker create -p3306:3306 --name myese -e MYSQL_ROOT_PASSWORD=toor mysql
```

#### Validate container creation

```bash
docker ps -a
```

<figure><img src="https://344105405-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFJ8sxzGfhnecDpAjrc%2Fuploads%2F5EE5b8TWgQ590vmsVraz%2Fimage.png?alt=media&#x26;token=06b7e501-abd5-4193-84fd-eb969d6ddb08" alt=""><figcaption><p>Docker container created</p></figcaption></figure>

#### Start container

```bash
docker start myese # or
docker start 0bd6cfe5a5e8
```

```bash
docker ps
```

<figure><img src="https://344105405-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFJ8sxzGfhnecDpAjrc%2Fuploads%2F45RDPtawBAD9iIQHM3Uu%2Fimage.png?alt=media&#x26;token=d0a150ec-3592-4a5d-bd04-e11c8764201a" alt=""><figcaption><p>Dockerr container started</p></figcaption></figure>

We have our container running (:

### Create a simple Python program to interact with MySQL

#### Install MySQL package

```bash
pip install mysql-connector-python
```

#### Connection to MySQL

This is our file, called `myappa.py`:

```bash
import mysql.connector

conn = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')

conn.close()
```

#### List databases

```python
import mysql.connector

conn = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
cursor = conn.cursor()

cursor.execute("SHOW DATABASES")

for database in cursor:
    print(database)

conn.close()
```

<figure><img src="https://344105405-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFJ8sxzGfhnecDpAjrc%2Fuploads%2FQhX09gcZ1EaHbeXgl2ch%2Fimage.png?alt=media&#x26;token=7963b161-1c1c-4926-aa3a-979d37cfd9f2" alt=""><figcaption><p>Databases</p></figcaption></figure>

#### Create a database

```bash
import mysql.connector

conn = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
cursor = conn.cursor()

cursor.execute("CREATE DATABASE test")
cursor.execute("SHOW DATABASES")

for database in cursor:
    print(database)

conn.close()
```

<figure><img src="https://344105405-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFJ8sxzGfhnecDpAjrc%2Fuploads%2FN3uhbQjAfRt7KMO25FjD%2Fimage.png?alt=media&#x26;token=ac6f9274-b0e7-4f46-a696-d003c8c52f91" alt=""><figcaption><p>Database 'test' created</p></figcaption></figure>

## Dockerize an external program

We'll take as example this code:

```python
import mysql.connector

conn = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
cursor = conn.cursor()

cursor.execute("CREATE DATABASE test")
cursor.execute("SHOW DATABASES")

for database in cursor:
    print(database)

conn.close()
```

To dockerize that, we need a **Dockerfile** file, in this case, we will have this content in it:

```docker
FROM python:3.12.2

RUN mkdir -p /home/app

COPY requirements.txt /home/app/requirements.txt
RUN pip3 install -r /home/app/requirements.txt

COPY . /home/app

EXPOSE 5000

CMD ["python3", "/home/app/myappa.py"]
```

And inside **requirements.txt** file, the list of our packages:

```
mysql-connector-python
```

Now, using the next command, we could create the image related to our program:

```bash
# docker build -t [custom_name]:[custom_tag] [route_Dockerfile]
docker build -t miapp:1 .
```

Finally, if everything is okay, we will see the image created:

```
❯ docker images
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
miapp        1         309ed83e6e7e   13 seconds ago   1.12GB
```

But this is not doing anything, because our image is connecting to host **127.0.0.1** of a **MySQL** container, but to connect containers we need a little more of knowledge.

Well, to make things work, we need to use networks.

## Connection between dockers containers

We need to use networks, with it container can talk between them:

```bash
docker network create mired
```

Now create the MySQL container:

```bash
docker pull mysql
docker create -p3306:3306 --name testdbs --network mired -e MYSQL_ROOT_PASSWORD=toor mysql
```

Now, create container of our app:

To this, change the host in our program:&#x20;

* Instead of **127.0.0.1**, we need to use the name of the container where (in this case) **MySQL** is running, so, host is now the name of that containe&#x72;**.**

```python
import mysql.connector

conn = mysql.connector.connect(user='root', password='toor', host='testdbs')
cursor = conn.cursor()

cursor.execute("CREATE DATABASE test")
print("Base de datos test creada")

print("Lista de bases de datos:")
cursor.execute("SHOW DATABASES")

for database in cursor:
    print(database)

conn.close()
```

And the **Dockerfile**:

```docker
FROM python:3.12.2

RUN mkdir -p /home/app

COPY requirements.txt /home/app/requirements.txt
RUN pip3 install -r /home/app/requirements.txt

COPY . /home/app

EXPOSE 5000

CMD ["python3", "/home/app/myappa.py"]
```

```bash
docker build -t miapp:1 .
```

```bash
docker create -p5000:5000 --name testmipyapp --network mired miapp:1
```

And these are our containers:

```bash
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS    PORTS     NAMES
a5f4610877d4   miapp:1   "python3 /home/app/m…"   2 seconds ago   Created             testmipyapp
89fea610bee4   mysql     "docker-entrypoint.s…"   6 minutes ago   Created             testdbs
```

First, start MySQL container:

```bash
docker start testdbs
```

Then, our app:

```bash
docker start testmipyapp
```

If we see the container logs of our program, we'll notice that execution was success:

```bash
docker logs testmipyapp
```

```bash
Base de datos test creada
Lista de bases de datos:
('information_schema',)
('mysql',)
('performance_schema',)
('sys',)
('test',)
```

> If you are having an error in the connection to the MySQL container, try start your app after some seconds, or check logs of MySQL container to know when the container is fully running.

Our containers are talking to each other, using networks (:
