I find that posture comes from strength in the right areas. A strong back tends to pull your shoulders back, which pushes your chest up. Your abdominal muscles create a solid wall up front, which keeps you upright. A strong lower back also helps to rock your chest up and keep you upright.
A lot of poor posture is caused by anterior pelvic tilt, typically from spending too much time sitting in chairs, things that should be tight are loose, and things that should be loose are tight.
You can read up on fixing them here, and a lot of it comes down to strength training. The big compound barbell lifts like back squat, over head press, deadlift, and row will do magical things for your posture (and much else).
I'd recommend checking out Starting Strength or Strong Lifts 5x5.
Additionally, try not to fall into the "23/1 trap", where you have one hour a day of great training and then spend the rest of your day causing the same problems to your body that got you into the mess.
Some other things that will make a big difference:
- Walk more. Whatever you have to do, spend more time on your feet moving around.
- Try to get an adjustable stand up desk. The kind you can raise up for a bit and then drop back down when you like.
- Get up and move as much as possible. It will be a little weird to do squats at your desk, but you honestly need to pick between being the weird fitness guy and being the slob with bad posture. There's not a lot of middle ground especially as you get older.
If your muscles are developed in a balanced way (courtesy of those programs I linked and which incorporate the lifts above), you stay active, and you move around, you'll have terrific posture.