It’s something I struggle with too. Like you, days when I get enough of a ride in usually aren’t a problem, but otherwise it can be a challenge for me to get a good night’s sleep. I also find melatonin doesn’t reliably work for me; it will work if I haven’t taken any for about a month, but if I take it nightly it seems to have no effect on my ability to sleep so I generally don’t bother with it any more.
A couple of things that are helping: I’ve taken a complete break from alcohol for a time and I’m sleeping a bit better as a result. I also stop consuming liquids of any sort rather early (say by 7:00 PM) to help reduce the need to get up in the middle of the night. I try to avoid anything that gets me worked up in the evening, so I avoid news, reading anything that is likely to get me agitated or anything like that.
Even though it’s not a source of serious exercise, I find going for a night time walk can help and I usually take the dog out for a couple of km before settling in.
None of these things guarantee I get a good night’s sleep, but they seem to help.