Flush all the content from Memcached via the CLI

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, January 06, 2015

Follow me on Twitter as @mattiasgeniar

Memcached is an easy to use key/value store run in memory of a server. It’s content is volatile, every restart of the Memcached service would remove all the data in memory and start anew.

But you can also flush the content (all keys and their values) from the command line, without restarting Memcached or additional sudo commands to grant non-privileged users permissions to flush the cache.

To flush the content, you can telnet to your Memcached instance and run the flush_all command.

$ telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

flush_all
OK

quit

Or in several one-liners that you can use in scripts, they rely on nc (netcat; yum install nc):

$ echo "flush_all" | nc localhost 11211
$ nc localhost 11211 <<< "flush_all"

As soon as the flush_all command is typed, all keys are set to expire. They won’t be dropped from memory actively (as this would be quite a “heavy” operation to drop every key), but they’re expired so the next retrieval would be invalid. This also means the flush_all doesn’t free memory on the server, it frees the memory in the memcached service.

As a bonus, here’s an nmap command that scans the entire IPv4 IP space for services that listen to port 11211. If you want to have fun, write a script that loops each IP and sends flush_all's to each service, every minute.

$ nmap 0.0.0.0/0 -p 11211 --open 2> /dev/null
...
Nmap scan report for something.tld (192.168.5.152)
PORT      STATE SERVICE
11211/tcp open  unknown
...

That’s the price you pay for not correctly limiting your Memcached services. ;-)



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.