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:
docker network create mired
Now create the MySQL container:
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:
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 container.
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:
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"]
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:
docker start testdbs
Then, our app:
docker start testmipyapp
If we see the container logs of our program, we'll notice that execution was success:
docker logs testmipyapp
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 (: