A piece of music in a key has committed to a particular scale and a particular home note. The key is the gravitational centre: the note the melody comes to rest on and the chord that sounds like the end.
Key signatures
Rather than marking every sharp or flat as it occurs, notation puts them once at the start of each line. That collection is the key signature, and it tells a player which notes are altered throughout.
C major needs no alterations at all, which is why it is where everyone starts. G major needs F sharp. D major needs F sharp and C sharp. Each new key adds exactly one.
The circle of fifths
Those additions follow a beautifully regular pattern. Go up a perfect fifth from C and you reach G, which needs one sharp. Up another fifth to D, two sharps. Up again to A, three. Keep going and after twelve fifths you arrive back at C, having visited every key.
Going the other way, down a fifth from C to F, adds flats at the same rate.

The circle is the single most useful diagram in music theory. Keys next to each other on it share almost all their notes, so moving between them is smooth, which is exactly why so much music modulates to the key a fifth above. Keys on opposite sides share few notes and moving between them is jarring, which is a tool in itself.
Relative and parallel
Every major key has a relative minor built on its sixth degree, using precisely the same notes and the same key signature. C major and A minor are written identically; what differs is which note behaves as home. This is why a piece can slip between bright and sombre without changing a single accidental.
A parallel minor shares the tonic instead, so C major and C minor start in the same place but have different signatures. Borrowing a chord from the parallel key is one of the oldest ways to darken a phrase without leaving home.
Modulation
Staying in one key for a long piece grows static, so composers modulate, shifting the centre of gravity mid-piece. Done well, the listener feels the ground move without being able to say when, and the eventual return to the original key lands like a homecoming.
A great deal of large-scale musical form is built from exactly this: establish a key, leave it, create tension by staying away, and resolve by coming back. The other dimension music organises is time.