<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Stefano Passador</title>
    <description>The latest articles on Forem by Stefano Passador (@stefanopassador).</description>
    <link>https://forem.com/stefanopassador</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F493901%2Fb60aa3a3-babd-4057-9c40-098b155f7946.jpeg</url>
      <title>Forem: Stefano Passador</title>
      <link>https://forem.com/stefanopassador</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/stefanopassador"/>
    <language>en</language>
    <item>
      <title>Docker Compose with Python and PosgreSQL</title>
      <dc:creator>Stefano Passador</dc:creator>
      <pubDate>Mon, 19 Oct 2020 08:17:54 +0000</pubDate>
      <link>https://forem.com/stefanopassador/docker-compose-with-python-and-posgresql-33kk</link>
      <guid>https://forem.com/stefanopassador/docker-compose-with-python-and-posgresql-33kk</guid>
      <description>&lt;p&gt;Docker helps developers create apps removing a lot of headaches about platform compatibility and dependencies.&lt;/p&gt;

&lt;p&gt;What I will show in this simple tutorial is the creation of a Docker application similar to the one available &lt;a href="https://docs.docker.com/compose/gettingstarted/"&gt;here&lt;/a&gt;. The main difference is that my version uses a PostgreSQL database instead of a Redis one.&lt;/p&gt;

&lt;p&gt;The prerequisite of the tutorial is to have Docker Engine and Docker Compose installed on your machine.&lt;/p&gt;

&lt;p&gt;The full repository of this tutorial is available &lt;a href="https://github.com/stefanopassador/Tutorial_DockerPythonPostgres"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;First thing you have to do is create a project folder (and the folder we will need later). You can do this by running the following commands from a Terminal view.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mkdir docker_python_sql_tutorial
$ cd docker_python_sql_tutorial
$ mkdir app
$ mkdir database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  PostgreSQL
&lt;/h2&gt;

&lt;p&gt;PostgreSQL is a free and open-source relational DBMS that is SQL compliant. It features transactions with ACID properties (Atomicity, Consistency, Isolation, Durability). We use it as a replacement of Redis, which is a data structure project implementing an in-memory key-value database with optional durability.&lt;br&gt;
For instantiating a PostgreSQL database through Docker we can use the official image. To do so I write the following &lt;code&gt;Dockerfile&lt;/code&gt; inside the folder &lt;code&gt;database&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight docker"&gt;&lt;code&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="s"&gt; postgres:latest&lt;/span&gt;
&lt;span class="k"&gt;ENV&lt;/span&gt;&lt;span class="s"&gt; POSTGRES_PASSWORD=secret&lt;/span&gt;
&lt;span class="k"&gt;ENV&lt;/span&gt;&lt;span class="s"&gt; POSTGRES_USER=username&lt;/span&gt;
&lt;span class="k"&gt;ENV&lt;/span&gt;&lt;span class="s"&gt; POSTGRES_DB=database&lt;/span&gt;
&lt;span class="k"&gt;COPY&lt;/span&gt;&lt;span class="s"&gt; create_fixtures.sql /docker-entrypoint-initdb.d/create_fixtures.sql&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this file we can get the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;FROM: this directive is used to identify the image from which we want to build the new image. I choose &lt;code&gt;postgres:latest&lt;/code&gt; which is the official Docker Image with the tag &lt;code&gt;latest&lt;/code&gt; that indicates the latest version (13).&lt;/li&gt;
&lt;li&gt;ENV: with this directive, we are able to specify various environment variables. For this image I specified &lt;code&gt;POSTGRES_PASSWORD, POSTGRES_USER, POSTGRES_DB&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;COPY: used to copy the file specified &lt;code&gt;create_fixtures.sql&lt;/code&gt; in a specific folder into the image created &lt;code&gt;/docker-entrypoint-initb.d/&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The copy of a file inside the folder &lt;code&gt;/docker-entrypoint-initb.d/&lt;/code&gt; is very useful because it allows us launch some initialization SQL commands. In this case, I’ve decided to create a simple table with two fields (see below).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;IF&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="k"&gt;EXISTS&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nb"&gt;timestamp&lt;/span&gt; &lt;span class="nb"&gt;BIGINT&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To try out the database through SQL commands you can run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ cd database/
# Create the docker image 
$ docker build . 
# Run the docker image and connect to it
$ docker run -it &amp;lt;image_id&amp;gt; bash
# Enter to the database
psql postgres://username:secret@localhost:5432/database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All of this concludes our configuration of the PostgreSQL database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Python
&lt;/h2&gt;

&lt;p&gt;Now, it’s time to create the Python script that will work together with the database. The created script (inside the &lt;code&gt;app&lt;/code&gt; folder) is the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;time&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;random&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sqlalchemy&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;create_engine&lt;/span&gt;

&lt;span class="n"&gt;db_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;'database'&lt;/span&gt;
&lt;span class="n"&gt;db_user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;'username'&lt;/span&gt;
&lt;span class="n"&gt;db_pass&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;'secret'&lt;/span&gt;
&lt;span class="n"&gt;db_host&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;'db'&lt;/span&gt;
&lt;span class="n"&gt;db_port&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;'5432'&lt;/span&gt;

&lt;span class="c1"&gt;# Connecto to the database
&lt;/span&gt;&lt;span class="n"&gt;db_string&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;'postgres://{}:{}@{}:{}/{}'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;db_user&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db_pass&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db_host&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db_port&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;create_engine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;db_string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_new_row&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="c1"&gt;# Insert a new number into the 'numbers' table.
&lt;/span&gt;    &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"INSERT INTO numbers (number,timestamp) "&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;\
        &lt;span class="s"&gt;"VALUES ("&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;\ 
        &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;","&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; \
        &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;");"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_last_row&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="c1"&gt;# Retrieve the last number inserted inside the 'numbers'
&lt;/span&gt;    &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;""&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; \
            &lt;span class="s"&gt;"SELECT number "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; \
            &lt;span class="s"&gt;"FROM numbers "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; \
            &lt;span class="s"&gt;"WHERE timestamp &amp;gt;= (SELECT max(timestamp) FROM numbers)"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;\
            &lt;span class="s"&gt;"LIMIT 1"&lt;/span&gt;

    &lt;span class="n"&gt;result_set&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;result_set&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;'__main__'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'Application started'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;add_new_row&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;randint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;100000&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'The last value insterted is: {}'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;get_last_row&lt;/span&gt;&lt;span class="p"&gt;()))&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we have done is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Define the parameters to create the connection string needed for the SQLAlchemy, which allows us to make the connection to PostgreSQL. As you can see, the &lt;code&gt;db_name, db_user, db_pass&lt;/code&gt; are the same indicated before as environment variables in the PostgreSQL Dockerfile. The &lt;code&gt;db_host&lt;/code&gt; variable will be explained later, and the &lt;code&gt;db_port&lt;/code&gt; is the default PostgreSQL port.&lt;/li&gt;
&lt;li&gt;Define two functions &lt;code&gt;add_new_row(n)&lt;/code&gt; that saves inside the database a new number n and &lt;code&gt;get_last_row()&lt;/code&gt; that retrieves the last number inserted inside the database.&lt;/li&gt;
&lt;li&gt;In the main section, I simply wrote an infinite loop that adds a new number in the database and then retrieves it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For making the python script work, we specified the dependencies in the &lt;code&gt;requirements.txt&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sqlalchemy
psycopg2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, to make the python part of this tutorial we create a Docker image through the Dockerfile inside the &lt;code&gt;app&lt;/code&gt; folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight docker"&gt;&lt;code&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="s"&gt; python:latest&lt;/span&gt;
&lt;span class="k"&gt;WORKDIR&lt;/span&gt;&lt;span class="s"&gt; /code&lt;/span&gt;
&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="s"&gt; requirements.txt requirements.txt&lt;/span&gt;
&lt;span class="k"&gt;RUN &lt;/span&gt;pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-r&lt;/span&gt; requirements.txt
&lt;span class="k"&gt;COPY&lt;/span&gt;&lt;span class="s"&gt; app.py app.py&lt;/span&gt;
&lt;span class="k"&gt;CMD&lt;/span&gt;&lt;span class="s"&gt; ["python", "-u", "app.py"]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some of the directives used this time are the same as before (FROM, COPY), the others are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;WORKDIR: Used to specify the working directory (where our COPY/ADD directives will copy files when no path is specified)&lt;/li&gt;
&lt;li&gt;ADD: Similar to the COPY directives (I won’t go into the details of the difference)&lt;/li&gt;
&lt;li&gt;RUN: Run a command during the building of the image. In this case, we install the libraries specified in &lt;code&gt;requirements.txt&lt;/code&gt; (that has already been copied into the image working directory)&lt;/li&gt;
&lt;li&gt;CMD: Similar to the RUN directive, but this is launch only when the image is started. It is the entrypoint of the image.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With this Dockerfile configuration, we also allow the caching of the requirements. This works because Docker uses its cache as long as the &lt;code&gt;requirements.txt&lt;/code&gt; file has not been changed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Put things together
&lt;/h2&gt;

&lt;p&gt;The final step of the tutorial is the union of the two images that we created. The most elegant way to do that is by creating a &lt;code&gt;docker-compose.yml&lt;/code&gt; file in the root of the project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;version&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="s"&gt;3.8"&lt;/span&gt;
&lt;span class="na"&gt;services&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;app &lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;./app/&lt;/span&gt;
  &lt;span class="na"&gt;db&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;./database/&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this we are declaring two containers inside our application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;app&lt;/strong&gt;: the one that is defined inside the &lt;code&gt;/app/Dockerfile&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;db&lt;/strong&gt;: the one in &lt;code&gt;/database/Dockerfile&lt;/code&gt;
With the services name, we understand the &lt;code&gt;db_host='db'&lt;/code&gt; inside the &lt;code&gt;app.py&lt;/code&gt;, it is Docker that manages the networking between the two images after being launched, so it translates the &lt;code&gt;db&lt;/code&gt; as the hostname of the database service.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The final command required to make everything run is &lt;code&gt;docker-compose up --build&lt;/code&gt;. This will build your images and then start the containers.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you have any tips, comments or questions, do not hesitate to ask me in the comments below.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>docker</category>
      <category>python</category>
      <category>postgres</category>
    </item>
  </channel>
</rss>
