The poem was a tribute to Abraham Lincoln, who had been assassinated in 1865, the year in which the poem was written.
The poem is divided into three stanzas. The first stanza begins in a celebratory mode, for the Civil War has been won by the Union:
O Captain! my Captain! our fearful trip is done,
The ship has weather’d every rack, the prize we sought is won,
The port is near, the bells I hear, the people all exulting.
The "fearful trip" is a metaphor for the war, and "the prize" is the continued existence of the Union.
The first stanza breaks after the fourth line to acknowledge the moment in which the President was shot.
The second stanza refers to his funeral, for which there are "bouquets and ribbon'd wreaths." His death, for the narrator, seems implausible: "It is some dream that on the deck, / You’ve fallen cold and dead."
In the third and final stanza, there is acknowledgement of the "captain['s]," or president's, mortality: "My Captain does not answer, his lips are pale and still, / My father does not feel my arm, he has no pulse nor will." Nevertheless, "the ship is anchor'd safe and sound, its voyage closed and done." In other words, the war is over. Additionally, "from fearful trip the victor ship comes in with object won." This means that the Union has been saved.
The poem is a lament for the death of Lincoln, coupled with relief that the Union has remained intact. He is our "captain" because he successfully led the nation during a very difficult time.