1. Get enough rest, especially sleep. Without enough rest, your mind has little time to defrag. Without defragging, it wanders off easily.
2. Let your mind wander, but not at work. Avoid social media and gaming as these give your brain more things to process. Games and social media are especially dangerous because you think you're taking a break but only make yourself more tired.
3. Don't do anything tiring before work. I found my work productivity increasing greatly by avoiding morning exercise. These tap into willpower reserves.
4. Avoid caffeine. YMMV, but I found that caffeine made it difficult for me to focus. Caffeine tends to be a counter for lack of sleep.
5. Train yourself to be bored. Part of the problem is that your brain is already trained to reach for something whenever bored. When you feel the urge to look at HN or Reddit, just give yourself at least a 5 min time gap, to consider whether you really need to. Even better if you could give yourself 30-60 min gaps between the urge and the action.
So you could:
* Switch to a more interesting project at work.
* Find a new job that's more compelling.
* Focus on second order motivations, like "I am making money to pay for food." This is harder.
More here: https://codewithoutrules.com/2017/08/03/stay-focused/