2

I am trying to link two docker containers (WordPress and mysql) by using the command line but it did not work.I have also tried with docker-compose.yml but only one container is working and I am unable to link both containers.I have used following commands.I am currently using AWS Amazon Linux AMI.

docker run --name db -e MYSQL_ROOT_PASSWORD=abc123 -p 3306:3306 -d mysql
docker run --name wordpress  --link db:mysql -p 80:80 -d wordpress.

After running these commands only one container (MYSQL) is active:

see image here

mzjn
  • 48,958
  • 13
  • 128
  • 248
  • Can you do execute `docker logs CONTAINERID` to see what the logs are? this might give you a hint on the error – ThomasVdBerge Apr 27 '18 at 12:40
  • I would assume your `wordpress` container crashes, so worth to look into its logs by looking up the original container id with `docker ps --all` to see previous ones too and then `docker logs ` – muratiakos Apr 27 '18 at 12:55
  • both image are mysql in the screenshot? – kakabali Apr 27 '18 at 12:55

1 Answers1

1

That's easily manageable if you setup a docker-compose.yml having both containers within the same network:

version: '3'
services:
  # Containers
  my_wp_container:
    # ...
    # Container config goes here
    # ...
    networks:
      # Make sure both containers are in the same network
      - my_network_name
    links:
      # "Linking" containers makes it easy to refer to one container from another
      - my_mysql_container

  my_mysql_container:
    # ...
    # Container config goes here
    # ...
    container_name: my_mysql_container
    networks:
      - my_network_name

networks:
  # No additional configuration is required for the network other than
  # creating it; You are of course free to customize it to your needs
  my_network_name:

Running docker-compose up will spin up both containers simultaneously. Your WordPress container (my_wp_container) can reach MySQL easily as my_mysql_container is now a host alias know to WP's container.

Once both containers are running, try SSH'ing into my_wp_container and running:

ping my_mysql_container

You should see that one container can reach the other within it's docker network!

mathielo
  • 6,725
  • 7
  • 50
  • 63
  • i am able to ping MySQL container but while installing i am getting same issue database hase not yet connected – Rakesh Sivagouni Apr 27 '18 at 15:43
  • @RakeshSivagouni Have you [enabled remote connections](https://stackoverflow.com/a/14779244) to MySQL? By default ot only accepts connections from the same host, and each container act as a different one. – mathielo Apr 27 '18 at 16:29