Running migrations for Symfony 2.8 during docker-compose build, but it works from the bash

I have a docker-compose.yml and a Dockerfile that create containers for an app in Symfony 2.8.

The containers are called: webserver (Nginx), app (Symfony) and db (MySql).

When I create the containers, I can easily access the bash of the app and run php app/console doctrine:migrations:migrate. Everything works fine.

I would like to insert the command in the Dockerfile, like this:

RUN cd /var/www && php app/console doctrine:migrations:migrate

but, when it arrives at that point, it just returns:

[DoctrineDBALExceptionConnectionException]                                                                                   
  An exception occured in driver: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known  

  [DoctrineDBALDriverPDOException]                                                             
  SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known  

  [PDOException]                                                                                  
  SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known  

  [PDOException]                                                                               
  PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known  

doctrine:migrations:migrate [--write-sql] [--dry-run] [--query-time] [--allow-no-migration] [--configuration [CONFIGURATION]] [--db-configuration [DB-CONFIGURATION]] [--db DB] [--em EM] [--shard SHARD] [--] [<version>]


ERROR: Service 'app' failed to build: The command '/bin/sh -c cd /var/www && php app/console doctrine:migrations:migrate' returned a non-zero code: 1

What could the problem be? It works after I access the bash in the container, but not automatically from the script.

Source: StackOverflow