Practical examples

Python external program using docker MySQL

Create MySQL container

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

Create container with config

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

Validate container creation

docker ps -a
Docker container created

Start container

Dockerr container started

We have our container running (:

Create a simple Python program to interact with MySQL

Install MySQL package

Connection to MySQL

This is our file, called myappa.py:

List databases

Databases

Create a database

Database 'test' created

Dockerize an external program

We'll take as example this code:

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

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

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

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

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:

Now create the MySQL container:

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.

And the Dockerfile:

And these are our containers:

First, start MySQL container:

Then, our app:

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

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 (:

Last updated