下载镜像

这里以5.0为例子

  1. docker pull redis:5.0

编写docker-compose.yml

  1. services:
  2. redis:
  3. image: redis:5.0
  4. container_name: redis
  5. restart: always
  6. volumes:
  7. - /home/data/redis/data:/data
  8. - ./redis.conf:/usr/local/etc/redis/redis.conf
  9. - /home/data/redis/logs:/logs
  10. command:
  11. # 两个写入操作 只是为了解决启动后警告 可以去掉
  12. /bin/bash -c "echo 511 > /proc/sys/net/core/somaxconn
  13. && echo never > /sys/kernel/mm/transparent_hugepage/enabled
  14. && redis-server /usr/local/etc/redis/redis.conf"
  15. ports:
  16. - 8307:6379
  17. environment:
  18. TZ: Asia/Shanghai

redis连接密码在conf文件里进行配置。

编写配置文件

对应版本的conf配置文件下载地址:
http://download.redis.io/releases/
示例配置文件如下:
最好打开redis的AOF和RDB持久化配置,两者结合使用。

  1. # Redis配置文件样例
  2. # Note on units: when memory size is needed, it is possible to specifiy
  3. # it in the usual form of 1k 5GB 4M and so forth:
  4. #
  5. # 1k => 1000 bytes
  6. # 1kb => 1024 bytes
  7. # 1m => 1000000 bytes
  8. # 1mb => 1024*1024 bytes
  9. # 1g => 1000000000 bytes
  10. # 1gb => 1024*1024*1024 bytes
  11. #
  12. # units are case insensitive so 1GB 1Gb 1gB are all the same.
  13. # Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程
  14. # 启用守护进程后,Redis会把pid写到一个pidfile中,在/var/run/redis.pid
  15. daemonize no
  16. # 当Redis以守护进程方式运行时,Redis默认会把pid写入/var/run/redis.pid文件,可以通过pidfile指定
  17. pidfile /var/run/redis.pid
  18. # 指定Redis监听端口,默认端口为6379
  19. # 如果指定0端口,表示Redis不监听TCP连接
  20. port 6379
  21. # 绑定的主机地址
  22. # 你可以绑定单一接口,如果没有绑定,所有接口都会监听到来的连接
  23. bind 0.0.0.0
  24. # Specify the path for the unix socket that will be used to listen for
  25. # incoming connections. There is no default, so Redis will not listen
  26. # on a unix socket when not specified.
  27. #
  28. # unixsocket /tmp/redis.sock
  29. # unixsocketperm 755
  30. # 当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能,单位为秒
  31. timeout 300
  32. # 指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认为verbose
  33. # debug (很多信息, 对开发/测试比较有用)
  34. # verbose (many rarely useful info, but not a mess like the debug level)
  35. # notice (moderately verbose, what you want in production probably)
  36. # warning (only very important / critical messages are logged)
  37. loglevel debug
  38. # 日志记录方式,默认为标准输出,如果配置为redis为守护进程方式运行,而这里又配置为标准输出,则日志将会发送给/dev/null
  39. logfile "/logs/redis.log"
  40. # To enable logging to the system logger, just set 'syslog-enabled' to yes,
  41. # and optionally update the other syslog parameters to suit your needs.
  42. # syslog-enabled no
  43. # Specify the syslog identity.
  44. # syslog-ident redis
  45. # Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
  46. # syslog-facility local0
  47. # 设置数据库的数量,默认数据库为0,可以使用select <dbid>命令在连接上指定数据库id
  48. # dbid是从0到‘databases’-1的数目
  49. databases 16
  50. ################################ SNAPSHOTTING #################################
  51. # 指定在多长时间内,有多少次更新操作,就将数据同步到数据文件,可以多个条件配合
  52. # Save the DB on disk:
  53. #
  54. # save <seconds> <changes>
  55. #
  56. # Will save the DB if both the given number of seconds and the given
  57. # number of write operations against the DB occurred.
  58. #
  59. # 满足以下条件将会同步数据:
  60. # 900秒(15分钟)内有1个更改
  61. # 300秒(5分钟)内有10个更改
  62. # 60秒内有10000个更改
  63. # Note: 可以把所有“save”行注释掉,这样就取消同步操作了
  64. save 900 1
  65. save 300 10
  66. save 60 10000
  67. # 指定存储至本地数据库时是否压缩数据,默认为yes,Redis采用LZF压缩,如果为了节省CPU时间,可以关闭该选项,但会导致数据库文件变的巨大
  68. rdbcompression yes
  69. # 指定本地数据库文件名,默认值为dump.rdb
  70. dbfilename dump.rdb
  71. # 工作目录.
  72. # 指定本地数据库存放目录,文件名由上一个dbfilename配置项指定
  73. #
  74. # Also the Append Only File will be created inside this directory.
  75. #
  76. # 注意,这里只能指定一个目录,不能指定文件名
  77. dir "/data"
  78. ################################# REPLICATION #################################
  79. # 主从复制。使用slaveof从 Redis服务器复制一个Redis实例。注意,该配置仅限于当前slave有效
  80. # so for example it is possible to configure the slave to save the DB with a
  81. # different interval, or to listen to another port, and so on.
  82. # 设置当本机为slav服务时,设置master服务的ip地址及端口,在Redis启动时,它会自动从master进行数据同步
  83. # slaveof <masterip> <masterport>
  84. # 当master服务设置了密码保护时,slav服务连接master的密码
  85. # 下文的“requirepass”配置项可以指定密码
  86. # masterauth <master-password>
  87. # When a slave lost the connection with the master, or when the replication
  88. # is still in progress, the slave can act in two different ways:
  89. #
  90. # 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will
  91. # still reply to client requests, possibly with out of data data, or the
  92. # data set may just be empty if this is the first synchronization.
  93. #
  94. # 2) if slave-serve-stale data is set to 'no' the slave will reply with
  95. # an error "SYNC with master in progress" to all the kind of commands
  96. # but to INFO and SLAVEOF.
  97. #
  98. slave-serve-stale-data yes
  99. # Slaves send PINGs to server in a predefined interval. It's possible to change
  100. # this interval with the repl_ping_slave_period option. The default value is 10
  101. # seconds.
  102. #
  103. # repl-ping-slave-period 10
  104. # The following option sets a timeout for both Bulk transfer I/O timeout and
  105. # master data or ping response timeout. The default value is 60 seconds.
  106. #
  107. # It is important to make sure that this value is greater than the value
  108. # specified for repl-ping-slave-period otherwise a timeout will be detected
  109. # every time there is low traffic between the master and the slave.
  110. #
  111. # repl-timeout 60
  112. ################################## SECURITY ###################################
  113. # Warning: since Redis is pretty fast an outside user can try up to
  114. # 150k passwords per second against a good box. This means that you should
  115. # use a very strong password otherwise it will be very easy to break.
  116. # 设置Redis连接密码,如果配置了连接密码,客户端在连接Redis时需要通过auth <password>命令提供密码,默认关闭
  117. requirepass "btez8MME1"
  118. # Command renaming.
  119. #
  120. # It is possilbe to change the name of dangerous commands in a shared
  121. # environment. For instance the CONFIG command may be renamed into something
  122. # of hard to guess so that it will be still available for internal-use
  123. # tools but not available for general clients.
  124. #
  125. # Example:
  126. #
  127. # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
  128. #
  129. # It is also possilbe to completely kill a command renaming it into
  130. # an empty string:
  131. #
  132. # rename-command CONFIG ""
  133. ################################### LIMITS ####################################
  134. # 设置同一时间最大客户端连接数,默认无限制,Redis可以同时打开的客户端连接数为Redis进程可以打开的最大文件描述符数,
  135. # 如果设置maxclients 0,表示不作限制。当客户端连接数到达限制时,Redis会关闭新的连接并向客户端返回max Number of clients reached错误信息
  136. # maxclients 128
  137. # Don't use more memory than the specified amount of bytes.
  138. # When the memory limit is reached Redis will try to remove keys with an
  139. # EXPIRE set. It will try to start freeing keys that are going to expire
  140. # in little time and preserve keys with a longer time to live.
  141. # Redis will also try to remove objects from free lists if possible.
  142. #
  143. # If all this fails, Redis will start to reply with errors to commands
  144. # that will use more memory, like SET, LPUSH, and so on, and will continue
  145. # to reply to most read-only commands like GET.
  146. #
  147. # WARNING: maxmemory can be a good idea mainly if you want to use Redis as a
  148. # 'state' server or cache, not as a real DB. When Redis is used as a real
  149. # database the memory usage will grow over the weeks, it will be obvious if
  150. # it is going to use too much memory in the long run, and you'll have the time
  151. # to upgrade. With maxmemory after the limit is reached you'll start to get
  152. # errors for write operations, and this may even lead to DB inconsistency.
  153. # 指定Redis最大内存限制,Redis在启动时会把数据加载到内存中,达到最大内存后,Redis会先尝试清除已到期或即将到期的Key,
  154. # 当此方法处理后,仍然到达最大内存设置,将无法再进行写入操作,但仍然可以进行读取操作。
  155. # Redis新的vm机制,会把Key存放内存,Value会存放在swap区
  156. # maxmemory <bytes>
  157. # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
  158. # is reached? You can select among five behavior:
  159. #
  160. # volatile-lru -> remove the key with an expire set using an LRU algorithm
  161. # allkeys-lru -> remove any key accordingly to the LRU algorithm
  162. # volatile-random -> remove a random key with an expire set
  163. # allkeys->random -> remove a random key, any key
  164. # volatile-ttl -> remove the key with the nearest expire time (minor TTL)
  165. # noeviction -> don't expire at all, just return an error on write operations
  166. #
  167. # Note: with all the kind of policies, Redis will return an error on write
  168. # operations, when there are not suitable keys for eviction.
  169. #
  170. # At the date of writing this commands are: set setnx setex append
  171. # incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
  172. # sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
  173. # zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
  174. # getset mset msetnx exec sort
  175. #
  176. # The default is:
  177. #
  178. # maxmemory-policy volatile-lru
  179. # LRU and minimal TTL algorithms are not precise algorithms but approximated
  180. # algorithms (in order to save memory), so you can select as well the sample
  181. # size to check. For instance for default Redis will check three keys and
  182. # pick the one that was used less recently, you can change the sample size
  183. # using the following configuration directive.
  184. #
  185. # maxmemory-samples 3
  186. ############################## APPEND ONLY MODE ###############################
  187. #
  188. # Note that you can have both the async dumps and the append only file if you
  189. # like (you have to comment the "save" statements above to disable the dumps).
  190. # Still if append only mode is enabled Redis will load the data from the
  191. # log file at startup ignoring the dump.rdb file.
  192. # 指定是否在每次更新操作后进行日志记录,Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一段时间内的数据丢失。
  193. # 因为redis本身同步数据文件是按上面save条件来同步的,所以有的数据会在一段时间内只存在于内存中。默认为no
  194. # IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
  195. # log file in background when it gets too big.
  196. appendonly yes
  197. # 指定更新日志文件名,默认为appendonly.aof
  198. # appendfilename appendonly.aof
  199. # The fsync() call tells the Operating System to actually write data on disk
  200. # instead to wait for more data in the output buffer. Some OS will really flush
  201. # data on disk, some other OS will just try to do it ASAP.
  202. # 指定更新日志条件,共有3个可选值:
  203. # no:表示等操作系统进行数据缓存同步到磁盘(快)
  204. # always:表示每次更新操作后手动调用fsync()将数据写到磁盘(慢,安全)
  205. # everysec:表示每秒同步一次(折衷,默认值)
  206. appendfsync everysec
  207. # appendfsync no
  208. # When the AOF fsync policy is set to always or everysec, and a background
  209. # saving process (a background save or AOF log background rewriting) is
  210. # performing a lot of I/O against the disk, in some Linux configurations
  211. # Redis may block too long on the fsync() call. Note that there is no fix for
  212. # this currently, as even performing fsync in a different thread will block
  213. # our synchronous write(2) call.
  214. #
  215. # In order to mitigate this problem it's possible to use the following option
  216. # that will prevent fsync() from being called in the main process while a
  217. # BGSAVE or BGREWRITEAOF is in progress.
  218. #
  219. # This means that while another child is saving the durability of Redis is
  220. # the same as "appendfsync none", that in pratical terms means that it is
  221. # possible to lost up to 30 seconds of log in the worst scenario (with the
  222. # default Linux settings).
  223. #
  224. # If you have latency problems turn this to "yes". Otherwise leave it as
  225. # "no" that is the safest pick from the point of view of durability.
  226. no-appendfsync-on-rewrite no
  227. # Automatic rewrite of the append only file.
  228. # Redis is able to automatically rewrite the log file implicitly calling
  229. # BGREWRITEAOF when the AOF log size will growth by the specified percentage.
  230. #
  231. # This is how it works: Redis remembers the size of the AOF file after the
  232. # latest rewrite (or if no rewrite happened since the restart, the size of
  233. # the AOF at startup is used).
  234. #
  235. # This base size is compared to the current size. If the current size is
  236. # bigger than the specified percentage, the rewrite is triggered. Also
  237. # you need to specify a minimal size for the AOF file to be rewritten, this
  238. # is useful to avoid rewriting the AOF file even if the percentage increase
  239. # is reached but it is still pretty small.
  240. #
  241. # Specify a precentage of zero in order to disable the automatic AOF
  242. # rewrite feature.
  243. auto-aof-rewrite-percentage 100
  244. auto-aof-rewrite-min-size 64mb
  245. ################################## SLOW LOG ###################################
  246. # The Redis Slow Log is a system to log queries that exceeded a specified
  247. # execution time. The execution time does not include the I/O operations
  248. # like talking with the client, sending the reply and so forth,
  249. # but just the time needed to actually execute the command (this is the only
  250. # stage of command execution where the thread is blocked and can not serve
  251. # other requests in the meantime).
  252. #
  253. # You can configure the slow log with two parameters: one tells Redis
  254. # what is the execution time, in microseconds, to exceed in order for the
  255. # command to get logged, and the other parameter is the length of the
  256. # slow log. When a new command is logged the oldest one is removed from the
  257. # queue of logged commands.
  258. # The following time is expressed in microseconds, so 1000000 is equivalent
  259. # to one second. Note that a negative number disables the slow log, while
  260. # a value of zero forces the logging of every command.
  261. slowlog-log-slower-than 10000
  262. # There is no limit to this length. Just be aware that it will consume memory.
  263. # You can reclaim memory used by the slow log with SLOWLOG RESET.
  264. slowlog-max-len 1024
  265. ################################ VIRTUAL MEMORY ###############################
  266. ### WARNING! Virtual Memory is deprecated in Redis 2.4
  267. ### The use of Virtual Memory is strongly discouraged.
  268. ### WARNING! Virtual Memory is deprecated in Redis 2.4
  269. ### The use of Virtual Memory is strongly discouraged.
  270. # Virtual Memory allows Redis to work with datasets bigger than the actual
  271. # amount of RAM needed to hold the whole dataset in memory.
  272. # In order to do so very used keys are taken in memory while the other keys
  273. # are swapped into a swap file, similarly to what operating systems do
  274. # with memory pages.
  275. # 指定是否启用虚拟内存机制,默认值为no,
  276. # VM机制将数据分页存放,由Redis将访问量较少的页即冷数据swap到磁盘上,访问多的页面由磁盘自动换出到内存中
  277. # 把vm-enabled设置为yes,根据需要设置好接下来的三个VM参数,就可以启动VM了
  278. # vm-enabled no
  279. # vm-enabled yes
  280. # This is the path of the Redis swap file. As you can guess, swap files
  281. # can't be shared by different Redis instances, so make sure to use a swap
  282. # file for every redis process you are running. Redis will complain if the
  283. # swap file is already in use.
  284. #
  285. # Redis交换文件最好的存储是SSD(固态硬盘)
  286. # 虚拟内存文件路径,默认值为/tmp/redis.swap,不可多个Redis实例共享
  287. # *** WARNING *** if you are using a shared hosting the default of putting
  288. # the swap file under /tmp is not secure. Create a dir with access granted
  289. # only to Redis user and configure Redis to create the swap file there.
  290. # vm-swap-file /tmp/redis.swap
  291. # With vm-max-memory 0 the system will swap everything it can. Not a good
  292. # default, just specify the max amount of RAM you can in bytes, but it's
  293. # better to leave some margin. For instance specify an amount of RAM
  294. # that's more or less between 60 and 80% of your free RAM.
  295. # 将所有大于vm-max-memory的数据存入虚拟内存,无论vm-max-memory设置多少,所有索引数据都是内存存储的(Redis的索引数据就是keys)
  296. # 也就是说当vm-max-memory设置为0的时候,其实是所有value都存在于磁盘。默认值为0
  297. # vm-max-memory 0
  298. # Redis swap文件分成了很多的page,一个对象可以保存在多个page上面,但一个page上不能被多个对象共享,vm-page-size是要根据存储的数据大小来设定的。
  299. # 建议如果存储很多小对象,page大小最后设置为32或64bytes;如果存储很大的对象,则可以使用更大的page,如果不确定,就使用默认值
  300. # vm-page-size 32
  301. # 设置swap文件中的page数量由于页表(一种表示页面空闲或使用的bitmap)是存放在内存中的,在磁盘上每8个pages将消耗1byte的内存
  302. # swap空间总容量为 vm-page-size * vm-pages
  303. #
  304. # With the default of 32-bytes memory pages and 134217728 pages Redis will
  305. # use a 4 GB swap file, that will use 16 MB of RAM for the page table.
  306. #
  307. # It's better to use the smallest acceptable value for your application,
  308. # but the default is large in order to work in most conditions.
  309. # vm-pages 134217728
  310. # Max number of VM I/O threads running at the same time.
  311. # This threads are used to read/write data from/to swap file, since they
  312. # also encode and decode objects from disk to memory or the reverse, a bigger
  313. # number of threads can help with big objects even if they can't help with
  314. # I/O itself as the physical device may not be able to couple with many
  315. # reads/writes operations at the same time.
  316. # 设置访问swap文件的I/O线程数,最后不要超过机器的核数,如果设置为0,那么所有对swap文件的操作都是串行的,可能会造成比较长时间的延迟,默认值为4
  317. # vm-max-threads 4
  318. ############################### ADVANCED CONFIG ###############################
  319. # Hashes are encoded in a special way (much more memory efficient) when they
  320. # have at max a given numer of elements, and the biggest element does not
  321. # exceed a given threshold. You can configure this limits with the following
  322. # configuration directives.
  323. # 指定在超过一定的数量或者最大的元素超过某一临界值时,采用一种特殊的哈希算法
  324. # hash-max-zipmap-entries 512
  325. # hash-max-zipmap-value 64
  326. # Similarly to hashes, small lists are also encoded in a special way in order
  327. # to save a lot of space. The special representation is only used when
  328. # you are under the following limits:
  329. list-max-ziplist-entries 512
  330. list-max-ziplist-value 64
  331. # Sets have a special encoding in just one case: when a set is composed
  332. # of just strings that happens to be integers in radix 10 in the range
  333. # of 64 bit signed integers.
  334. # The following configuration setting sets the limit in the size of the
  335. # set in order to use this special memory saving encoding.
  336. set-max-intset-entries 512
  337. # Similarly to hashes and lists, sorted sets are also specially encoded in
  338. # order to save a lot of space. This encoding is only used when the length and
  339. # elements of a sorted set are below the following limits:
  340. zset-max-ziplist-entries 128
  341. zset-max-ziplist-value 64
  342. # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in
  343. # order to help rehashing the main Redis hash table (the one mapping top-level
  344. # keys to values). The hash table implementation redis uses (see dict.c)
  345. # performs a lazy rehashing: the more operation you run into an hash table
  346. # that is rhashing, the more rehashing "steps" are performed, so if the
  347. # server is idle the rehashing is never complete and some more memory is used
  348. # by the hash table.
  349. #
  350. # The default is to use this millisecond 10 times every second in order to
  351. # active rehashing the main dictionaries, freeing memory when possible.
  352. #
  353. # If unsure:
  354. # use "activerehashing no" if you have hard latency requirements and it is
  355. # not a good thing in your environment that Redis can reply form time to time
  356. # to queries with 2 milliseconds delay.
  357. # 指定是否激活重置哈希,默认为开启
  358. activerehashing yes
  359. # 如果想让其他服务器访问需要关闭保护模式
  360. protected-mode no
  361. ################################## INCLUDES ###################################
  362. # 指定包含其他的配置文件,可以在同一主机上多个Redis实例之间使用同一份配置文件,而同时各实例又拥有自己的特定配置文件
  363. # include /path/to/local.conf
  364. # include /path/to/other.conf

简化版本:

  1. bind 0.0.0.0
  2. daemonize no
  3. pidfile "/var/run/redis.pid"
  4. port 6379
  5. timeout 300
  6. loglevel warning
  7. logfile "/logs/redis.log"
  8. databases 16
  9. rdbcompression yes
  10. dbfilename "redis.rdb"
  11. dir "/data"
  12. requirepass "btez8MME1"
  13. maxclients 10000
  14. maxmemory 1000mb
  15. maxmemory-policy allkeys-lru
  16. appendonly yes
  17. appendfsync everysec

启动服务

  1. docker-compose up -d

本地连接验证

  1. docker exec -it redis redis-cli

之后输入

  1. auth 你的密码

返回OK证明可以正常连接。