This short article will show you how to use Redis on Docker (docker-compose.yml) and how to connect in in the PHP. We are using the Predis library so that we need to install the dependency first by running the following composer command.
composer require predis/predis
Then we need to put the Redis image in our docker-compose.yml file as follow.
redis:
image: redis:4.0
container_name: app_redis
ports:
- "6382:6379"
networks:
- app-network
As you can see, It is on the app-network, so that I will need to declare the network too.
networks:
app-network:
driver: "bridge"
If we spin up the docker, the Redis will be running on the port 6379.
We can connect to the Redis as follow.
Setting the value.
try {
$redis = new \Predis\Client([
'host' => env('REDIS_HOST', '') // docker container name, app_redis
]);
$redis->set('name', 'Wai Yan Hein');
} catch (Exception $e) {
}
Retrieving the value.
try {
$redis = new \Predis\Client([
'host' => env('REDIS_HOST', '') // docker container name, app_redis
]);
return $redis->get('name');
} catch (Exception $e) {
}
You can also specify the port, schema and other variables for the client. That’s it. That is how we use Redis with Docker in PHP.