Follow these steps to connect to a database in a Docker container:
1. Start the Docker Daemon:
Open a terminal and start the Docker daemon. The Docker daemon listens for Docker API requests and manages Docker objects such as images, containers, networks. \`\`\` sudo service docker start \`\`\`1. Run your database in a Docker container:
\`\`\`bash docker run —name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -p 3306:3306 -d mysql \`\`\` This command does several things: - `docker run` creates a new container. - `—name` assigns a name to the container. - `-e` sets environment variables (`MYSQL_ROOT_PASSWORD`). - `-p` publishes the container’s port(s) to the host. - `-d` runs the container in detached mode. - `mysql` is the name of the image from Docker Hub to base the container on.1. Identify your Docker container’s IP address:
You can check the IP address assigned to your running Docker container using the `docker inspect` command: \`\`\`bash docker inspect1. Connect to your database:
Now, you need to use a tool or programming language to connect to your database.- For MySQL/MariaDB, you might use the `mysql` command which is included in those databases:
\`\`\`bash mysql -h- `mysql` is the MySQL command line tool.
- `-h` is the IP address to connect to (the Docker container’s IP).
- `-P` is the port to connect on which Docker has mapped and exposed.
- `-u` is the user that you’re connecting as.
- `-p` will cause MySQL to prompt you for your password.
Or you can use the localhost (127.0.0.1) instead of the docker-ip-address if the container port is mapped to the host:
```
mysql -h 127.0.0.1 -P
```
For programming languages you usually use a connection string:
- Python Example:
```
import mysql.connector
cnx = mysql.connector.connect(user=‘root’, password=‘my-secret-pw’,
host=‘127.0.0.1’,
database=‘test’)
cnx.close()
```
Just replace `host` and `port` with the details of your Dockerized database.
Replace `user` and `password` with the credentials for your database. Replace `database` with the name of your database. Replace `127.0.0.1` with your Docker container’s IP address if it is not mapping ports to the host.