Member-only story
This quick article will show you how to configure Redis on Docker in Laravel for caching. First, you need to install the Predis library by running the following composer command.
composer require predis/predis
Then you need to declare the Redis image in the docker-compose.yml file as follows.
redis:
image: redis:4.0
container_name: app_redis
ports:
- "6382:6379"
networks:
- app-network
As you can see, it is on a network called app-network, so we need to declare the network in the docker-compose.yml file as follows.
networks:
app-network:
driver: "bridge"
Then we need to set the environment variables in the .env file as follows.
CACHE_DRIVER=redis
REDIS_CLIENT=predis
REDIS_HOST=app_redis
REDIS_PASSWORD=null
REDIS_PORT=6379
The REDIS_HOST variable is set with the container name. Something we should pay attention to here is that REDIS_PASSWORD=null. If we do not set the password to null, it won’t work.
Then we can set the cache as follow in our code.
cache()->set('name', 'Wai');
Then, we can retrieve it back as follow.
\Illuminate\Support\Facades\Cache::get('name');
That’s it. That is how we use Redis on Docker in Laravel.